Home > Programming, Web Programming, WordPress > Automatic login into WordPress

Automatic login into WordPress

August 3rd, 2009 Leave a comment Go to comments

To make a WordPress private, it seemed like using an .htaccess would be the most straight-forward and secure approach. However, you end up having to type in your username name and password twice – once to get access to the web page (web server authentication) and once more to log into WordPress.

I googled a bit and ended up on this post by Leon Bukhman. In his case, he wanted automatic login to a “guest” account. I changed the code a bit and got it working with the REMOTE_USER environment variable (this is set by the webserver).

The full PHP script for WordPress is available at

You still have to create two accounts:

  1. An entry in the .htaccess file for logging
  2. An account with the same username for the WordPress.

When you log into the website, you will be logged into WordPress with the same username. You can still log-out of WordPress (you’ll be directed to the login page) and log-in with a different name (e.g. admin).

Here’s the script for the plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function auto_login()
{
    if (!is_user_logged_in())
    {
        $user_login = getenv("REMOTE_USER");

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

                //login
                wp_set_current_user($user_id, $user_login);
                wp_set_auth_cookie($user_id);
                do_action('wp_login', $user_login);
            }
        }
    }
}

add_action('init', 'auto_login');
Categories: Programming, Web Programming, WordPress Tags:
  1. September 15th, 2010 at 14:10 | #1

    Nice piece of code, I did use a slightly modified version of it for one of my customer.

  2. Mansi
    August 27th, 2012 at 07:45 | #2

    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?

  3. Gustaf
    August 28th, 2012 at 09:59 | #3

    Mansi, go to http://bazaar.enseed.com/utils/wordpress/plugins/autologin/ and download the plugin and put it in the wp-content/plugins directory.

  1. No trackbacks yet.
*

Please leave these two fields as-is:

Protected by Invisible Defender. Showed 403 to 108,244 bad guys.