Allow WordPress automatic login via a given URL

I finally found out how to allow an automatic login in WordPress via a given URL. This can be useful in order to keep some of your blog posts/pages hidden from the public, however, you still can share them with friends and family via a simple link.

  1. Create a subscriber user.
  2. Install the plugin WP Admin No Show – you can configure the plugin to block access of subscribers to the WordPress admin backend.
  3. Place the following snipplet of code into some file on your server (e.g., wp-autologin.php) and make an include ‘PATHTOFILE/wp-autologin.php’ in the functions.php file of your favorite theme:
<?php
function auto_login() {
        $user_login = $_GET['login'];
        $secret_token = 'SOMESECRETTOKEN';
        $loginusername = 'asubscriber';
        if ($user_login == $secret_token) {
                //get user's ID
                $user = get_user_by('login', $loginusername);
                $user_id = $user->ID;
                // let user read private posts
                if (!$user->has_cap('read_private_posts')) {
                        $user->add_cap('read_private_posts');
                }                                                           
                //login
                wp_set_current_user($user_id, $loginusername);
                wp_set_auth_cookie($user_id);
                do_action('wp_login', $loginusername);
        } 
}
add_action('init', 'auto_login');
?>

Now you only need to add ?login=SOMESECRETTOKEN to your url (e.g., http://blog.example.com/somepage?login=SOMESECRETTOKEN). Then, all posts marked as private will be visible to the particular subscriber account that you have created.

4 Comments

  1. Orwell says:

    Klasse. Danach hab ich jetzt zwei Tage gesucht. :)

    Cool wäre es noch, wenn unterschiedliche User unterschiedliche Tokens bekommen könnten, – für unterschiedliche Inhalte. – Ich bin kein Programmierer – leider :)

    Besten Dank also, – gute Arbeit.

  2. Willem says:

    Is this still relevant?

  3. Alex says:

    @Willem: As far as I can tell, yes. I am not aware of any built-in features with current versions. If you know, please tell me :) .

  4. willem says:

    I added it but it seems to login the user I add to it everytime even if i don’t add anything to the URL. Thank you for you reply though.

Leave a Comment

November 3, 2014 Development