Warning: count(): Parameter must be an array or an object that implements Countable in /homepages/31/d299190328/htdocs/wordpress/wp-includes/post-template.php on line 275

Warning: count(): Parameter must be an array or an object that implements Countable in /homepages/31/d299190328/htdocs/wordpress/wp-includes/post-template.php on line 275

Warning: count(): Parameter must be an array or an object that implements Countable in /homepages/31/d299190328/htdocs/wordpress/wp-includes/post-template.php on line 275

Warning: count(): Parameter must be an array or an object that implements Countable in /homepages/31/d299190328/htdocs/wordpress/wp-includes/post-template.php on line 275
Leon's Weblog

December 10, 2007

WordPress Auto-Login

Filed under: Software Dev — Leon @ 9:31 pm

WordPress is a great blogging engine. It’s flexible, scalable, and easy to tweak/configure to integrate into an existing PHP site. However, if you have an existing site with available user authentication and management capabilities, getting WordPress to accept those credentials (in a single sign-on fashion) can be a bit of a challenge.

Before we proceed, I should note that there are a number of available plugins that enable WordPress to integrate with some of the popular content management systems out there. Our requirement is a bit different however. We want to bypass WordPress’ authentication mechanism all together and have users login through the main portion of the site. In fact, in a well integrated site, the interface should make navigating between WordPress pages and the rest of the site seamless to the user. Our goal is to write a WordPress plug-in that will automatically authenticate a user who is already logged into the parent site (and, consequently, grant the user access to edit the blog’s content). All other users will have the rights of an unregistered visitor.

In my setup, the main site has role-based permissions and the WordPress setup only has one account for each role (i.e. admin, editor, user etc…). The plugin first checks the role of the user logged in to the main site and then simulates a WordPress login anytime the user navigates to the blog. You should be able to customize this method for your own needs.

function auto_login() {
    if (!is_user_logged_in()) {
        //determine WordPress user account to impersonate
        $user_login = 'guest'; 

        //get users password
        $user = new WP_User(0, $user_login);
        $user_pass = md5($user->user_pass); 

        //login, set cookies, and set current user
        wp_login($user_login, $user_pass, true);
        wp_setcookie($user_login, $user_pass, true);
        wp_set_current_user($user->ID, $user_login);
add_action('init', 'auto_login');

Additional notes and caveats for the attentive reader

  • There is a wp-include/pluggable.php file that defines all the functions that you can override and hook into. The WordPress API documentation is not very thorough so you may need to review the actual code.
  • WordPress uses a double MD5 hash of the password to authenticate the user. In the database, the password is stored as a single hash. We need to hash that password again before passing it into the wp_login() function (and set the third parameter to indicate that the password is already hashed). Obviously hard coding the actual password would be a big no-no.

We did all this work to login but what about logging out? We have several options. First, we can call WordPress’ logout method which is wp_clearcookie() from the main site.  The drawback to this approach is that we need to include all the WordPress libraries into our main site for this to work (too much unnecessary overhead IMHO). The other approach is to not use cookies at all thus alleviating the need to logout. To do this we simply remove the call to wp_setcookie() in out plugin and override the auth_redirect() function to do nothing. This works because we impersonate the user on every page load and the only WordPress code that checks the cookie was in auth_redirect() until we got rid of it. Another side effect of this is that un-authenticated WordPress users will no longer be taken to the WordPress login page (but we didn’t want that anyway).

Update 6/4/08: There were a few changes to the WordPress API as of version 2.5 and some of the functions I used above became depreciated. The API documentation has also improved. A better way to implement the auto_login() function above is as follows.

function auto_login() {
    if (!is_user_logged_in()) {
        //determine WordPress user account to impersonate
        $user_login = 'guest';

       //get user's ID
        $user = get_userdatabylogin($user_login);
        $user_id = $user->ID;

        wp_set_current_user($user_id, $user_login);
        do_action('wp_login', $user_login);
add_action('init', 'auto_login');

Update 4/15/13: WordPress’ popularity is making it a target for security attacks. At least this is the news that has been floating around lately. It is a good idea to create your own user accounts and delete the default accounts that come with WordPress. This (and strong passwords) will make it harder for scripted, brute force attacks on your site. Don’t forget to update the AutoLogin script accordingly. Here is a quick guide for deleting the admin account without loosing your posts.

Warning: count(): Parameter must be an array or an object that implements Countable in /homepages/31/d299190328/htdocs/wordpress/wp-includes/class-wp-comment-query.php on line 405


  1. Samuel, I haven’t tried the plug-in under WP 3. The API may have changed. When I get a chance to upgrade my site I’ll post an update if anything changes.

    Comment by leon — July 30, 2010 @ 5:40 pm
  2. Sorry, tinkered around, and realized it’s my oversight (expecting sessions to be carried over from main site to sub-sites). Thank you very much, the script now works, and thanks for responding. At least you know yours will work when you decide to upgrade to WP 3.

    Comment by Samuel Anyaele — July 31, 2010 @ 10:38 am
  3. Hi,its a gr8 idea for auto login.and its working fine when i use $user_login = ‘admin’ static;
    I have integrated wordpress on my site and created this auto_login in plugins but i need to pass username from site login dynamically please Help.

    Comment by paramjit — August 2, 2010 @ 2:26 am
  4. thanks a lot…. u saved my time…

    Comment by sunil — September 16, 2010 @ 2:55 am
  5. I’m new to this but where does this script go and what script does it replace?

    Comment by Rich — September 19, 2010 @ 11:17 pm
  6. Hey Samuel Anyaele

    May I request you to kindly share the code how you got it working on WordPress 3.0

    I am also having issues getting this to work.

    Thanks in advance

    Comment by Vikram — October 19, 2010 @ 8:20 am
  7. Thanks for this wonderful piece of code. I have been looking for it for a while. Only question I have is how are you passing $user_login to auto_login method or to this plugin. I have wrodpress installed as one of sub-domains and my parent site is java/j2ee based.

    Comment by Vikalp — October 30, 2010 @ 6:12 am
  8. good piece of code, one thing:

    logs the user in, when you click site admin from the theme front page it goes to wp-admin/ fine, but if you try to directly access /wp-admin/ it sends a redirect to the login form, using 3.0.1 wordpress.

    any ideas?

    Comment by chris — October 30, 2010 @ 11:05 am
  9. Hi.
    I found this at time when I need it.

    If I point to /wp-admin then it redirect to login page. when you visit site and then click on My Admin then it login to website.
    I found that cookie are not set in first case, when you point to page first then cookie are set and you can login to admin area.

    Use FF clear cookie, point browser to wp-login.php and check cookie, now you will see entry for login cookie, then you can point to wp-admin and you will be in.

    Any idea how to login directly to admin area?
    Thank you

    Comment by Mariusz — November 9, 2010 @ 11:14 pm
  10. Leon, thanks for this information. It’s helpful as I am looking for ways to login through external php scripts to the WordPress engine.

    Comment by Richard Cummings — November 29, 2010 @ 8:09 am
  11. […] WordPress Auto Login Function Posted by Soul on December 11, 2010 Leave a comment (0) Go to comments auto login a wordpress user function View Source or Documentation […]

    Pingback by WordPress Auto Login Function | The Code Library — December 11, 2010 @ 11:38 am
  12. Thanks a lot. It was very useful.

    Comment by vito spericolato — December 15, 2010 @ 10:17 am
  13. Real good post, great to hear about your experience

    Comment by Jogn — December 18, 2010 @ 1:31 pm
  14. Hi,
    I want to autologin everybody that click on links (that lead to my site) on a certain URL. So, If a link to my page is published on http://www.domain.com the person clicking it should be logged in autoamtically with a certain user.

    If the same link is somewhere else the one who clicks it shall not be logged in.

    Any suggestions on how to do this? Possible?
    many thanks.

    Comment by Ola Karlsson — January 25, 2011 @ 3:20 pm
  15. thanks for this information. It’s helpful as I am looking for ways to login through external php scripts to the WordPress engine

    Comment by onceso — February 4, 2011 @ 8:48 am
  16. Hi Leon!

    You have a lot of awesome information on this blog. Thank you for sharing it. Like one of the posts above, I’m trying to pass a user name and password from a .Net site to a WordPress 3.1+ site. I would like to use the functionality above but don’t know which session variables on the .Net site to use. If the .Net site sends me an encrypted user name and password, can I decrypt it by placing the encryption code from the .Net site into the PHP?

    Thanks in advance for any information,

    Comment by Linda — March 25, 2011 @ 7:56 pm
  17. Linda, it depends on how important security is to the site because you will have to store the authentication credentials in an inherently insecure location (e.g. inside the page as a post/get variable or in a secure cookie).

    Comment by leon — March 25, 2011 @ 8:28 pm
  18. Leon,

    Assuming that we can work around that acceptably, how does the .Net code talk to the WordPress PHP code in order to exchange the user information. Another developer in my company works with the .Net environment. I am a technical writer working with WordPress. Are there system variales known by both .Net and WordPress/PHP? For example:

    .Net moves username and user password to $variable1 and $variable2 respectively.
    WordPress PHP reads $variable1 and $variable2 values into $_Postvar1 and $_Postvar2 respectively.

    Comment by Linda — March 28, 2011 @ 5:58 am
  19. Linda, to my knowledge there is no built in way to have PHP and .Net code communicate. However, you can build this yourself. For example, if you view the HTML output of a .Net page you will see the hidden “__VIEWSTATE” control. You can create a parser to translate this encoded information in PHP. Or, simply create another hidden variable in the page that both .Net and PHP and access (you may want to encrypt this information).

    Comment by leon — March 28, 2011 @ 2:48 pm
  20. […] lbsharp.com Share and Enjoy: These icons link to social bookmarking sites where readers can share and […]

    Pingback by Enable WordPress Auto-Login | TechniTip.Net — March 31, 2011 @ 1:42 pm
  21. Hi Leon.

    Thanks for your posting of the auto login. But I am afraid I cannot get it to work. I have put it in a .php file and placed it in the plugins directory and activated it via the admin tool. I have changed $user_login = $_SESSION[‘MM_MemberID’]; which contains the id of the site use which is also the WP id. I am unclear as to how to get it to execute. I have an iFrame that has a link: The only thing that happens is the Hello World page comes up and then I have to click the Log In link that takes me to the login page where I have to input my id and pw. I sure woudld appreciate some of your kindness in helping me to get this auto login to work. I know I am doing something stupid but I need a WP guru like you to point it out. Thanks. Tombo.

    Comment by Tombo — April 22, 2011 @ 6:08 pm
  22. Nevermind! I figured it out. My session variables were empty due to not establishing a session under WP before I referenced them.

    Comment by Tombo — April 22, 2011 @ 7:38 pm
  23. Hi Leon, Tombo, and everybody,

    Tombo, I had the same experience that you have described above, how you solved the problem of session variables?

    How to establish a session with wp before refered it, i´m using xml rpc calls to access functions exposes through wp, i can add a user, list, update, but a i can´t login a user, i don´t know why,

    I thank you,

    Comment by Fabricio — May 29, 2011 @ 12:45 pm
  24. hello

    i try to us your code on wp 3.01 put dont make it work

    i am looking for an auto login from another site, not wordpress.
    juste one user is ok


    Comment by charly — July 27, 2011 @ 9:48 am
  25. i tried it also but don’t work in new version 3.2.1
    plz can u tell me the exact problem or anything i missed?

    my role was one pass for one time login.


    Comment by Monjurul Hoque — November 29, 2011 @ 1:42 pm
  26. I just implemented this into my plugin. Running WP 3.3 and BuddyPress 1.5.2 Took me all but 5 mins.

    It works great! I need to tweak it to get it to thoroughly authenticate in BuddyPress, but it got me to a 98% completion in 5 minutes time. I have been searching for days on the right action hooks to use and came up empty at all turns.

    Excellent script Leon! Thanks.

    Comment by Ed — January 11, 2012 @ 2:49 pm
  27. Hi

    How can this script be modified to detect the username of the person logged onto the computer (i.e. network username) so that it can be used against a WPMU site username to automate login ?

    Any help would be great

    Comment by DJW — January 12, 2012 @ 7:14 am
  28. Thank you so much.
    It work great in my case. You saved my hours….

    Comment by Moiz Shabbir — January 31, 2012 @ 10:18 am
  29. I am relatively new to PHP Scripting. How do I implement this function. Thanks

    Comment by Charles — February 4, 2012 @ 6:19 am
  30. Hi Leon,

    This is perfect and I’m so close to doing what I want it to do. The only thing is that I want to pull the username from the URL using $_GET, but when replacing the string ‘admin’ with the same string ‘admin’ from my $_GET variable, it doesn’t work. Very strange… I know I must be missing something.

    function auto_login() {
    // this works perfectly
    $user_login = ‘admin’;

    // this does not work even when setting the same variable via query string ?user=admin
    // $user_login = $_GET[‘user’];

    //get user’s ID
    $user = get_userdatabylogin($user_login);
    $user_id = $user->ID;

    wp_set_current_user($user_id, $user_login);
    do_action(‘wp_login’, $user_login);
    add_action(‘init’, ‘auto_login’);

    Would you mind giving me a tip if you see anything? Thanks in advance for your help!


    Comment by Ted — February 18, 2012 @ 10:09 pm
  31. Hi Ted,

    You probably don’t want to store the user name in the query string. Even if this worked, anyone could just pass in the user name to the page and get authenticated. I think the reason why this approach doesn’t work is that the query string is not available at the time WordPress loads the plugins.

    That said, I would store the username in the $_SESSION variable so that it will be available anywhere. Don’t forget to start the session before using the variable. The following reference will help: http://www.php.net/manual/en/book.session.php

    Good luck,

    Comment by leon — February 19, 2012 @ 10:37 am
  32. Ted, I was just wondering today for the first time if something like this was possible. Your post made it a reality and works well for programmatic entering of a single user name. Have you figured out the session implementation?

    Comment by Greg — February 27, 2012 @ 1:43 am
  33. Thank you very much Ted – this work like a charm
    have a good day


    Comment by arne — April 10, 2012 @ 6:34 am
  34. How come will not the hyperlinks on the top bar of the website webpage that post a comment work for me? Appreciate it

    Comment by Marilynn Walkers — April 28, 2012 @ 6:06 pm
  35. Hi, thanks for the post!!
    One question: How will I share the username from my external page to the auto_login() function?
    I tried
    in the first page and
    echo $_SESSION[‘test’];
    in auto_login function, but nothing is displayed on the screen..

    Thank you very much

    Comment by Kostas — May 29, 2012 @ 9:27 am
  36. Hello, I am new to wordpress. So i don’t know how to deal with this function. I know PHP. So would you please tell me the step by step procedure for getting worked this code. And another question is that do i need to change the code in my existing php website for getting this plugin work?

    Thanks in advanced.

    Comment by Mandi — August 27, 2012 @ 6:29 am
  37. […] Function Reference/wp signon WordPress Auto-Login […]

    Pingback by WordPress??????????? – ???? — May 16, 2013 @ 1:55 am
  38. This does the job nicely:

    Auto Login to WordPress site – maintains cookie and session (persistent)
    * Do not try to use CURL to do this as that’s on the server side cannot pass cookies to the browser client.

    Comment by Al — November 28, 2013 @ 11:10 pm
  39. I have the following code in my themes function file

    function auto_login() {
    /*if (!is_user_logged_in()) {
    //determine WordPress user account to impersonate
    $user_login = $_SERVER[‘REMOTE_USER’];

    //get users password
    $user = new WP_User(0, $user_login);
    $user_pass = md5($user->user_pass);

    //login, set cookies, and set current user
    wp_set_auth_cookie($user_login, $user_pass, true);
    wp_set_current_user($user->ID, $user_login);
    wp_signon($user_login, $user_pass, true);

    // Automatic login //
    $user = get_user_by(‘login’, $username );

    // Redirect URL //
    if ( !is_wp_error( $user ) )
    wp_set_current_user ( $user->ID );
    wp_set_auth_cookie ( $user->ID );

    //$redirect_to = user_admin_url();
    //wp_safe_redirect( $redirect_to );

    if (!is_user_logged_in()) {
    $user_login = (isset($_SERVER[‘REMOTE_USER’])) ? $_SERVER[‘REMOTE_USER’] : $_SERVER[‘PHP_AUTH_USER’] . “@DOMAIN.COM”;
    $user = get_userdatabylogin($user_login);
    $user_id = $user->ID;
    wp_set_current_user($user_id, $user_login);
    do_action(‘wp_login’, $user_login);

    add_action(‘init’, ‘auto_login’);

    However when i clear memcache and cache files and open my site i see the cache log saying i am anonymous user. I am using plugins: supercache, memcache, http-authentication, members only.

    Comment by sharif — April 10, 2014 @ 5:33 am
  40. […] Function Reference/wp signon WordPress Auto-Login […]

    Pingback by API?? | WordPress???????? — August 25, 2015 @ 11:43 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment