Skip to content

Instantly share code, notes, and snippets.

@webmasterninjay
Forked from cliffordp/functions.php
Created December 16, 2021 16:08
Show Gist options
  • Save webmasterninjay/51fcfa567d6d8b8a9220611cc1502793 to your computer and use it in GitHub Desktop.
Save webmasterninjay/51fcfa567d6d8b8a9220611cc1502793 to your computer and use it in GitHub Desktop.
Automatically login a single WordPress user upon arrival to a specific page.
<?php
/**
* Automatically login a single WordPress user upon arrival to a specific page.
*
* Redirect to home page once logged in and prevent viewing of the login page.
* Compatible with WordPress 3.9.1+
* Updated 2014-07-18 to resolve WP_DEBUG notice: "get_userdatabylogin is deprecated since version 3.3! Use get_user_by('login') instead."
* Updated 2019-07-09 to reformat code, pass 2nd parameter to `do_action()`, and hook into priority 1.
*
* @link https://gist.github.com/cliffordp/e8d1d9f732328ba360ad This snippet.
* @link http://tourkick.com/2014/wordpress-demo-multisite-db-reset/ An article that uses this snippet.
*/
function auto_login() {
// @TODO: change these 2 items
$loginpageid = '1234'; //Page ID of your login page
$loginusername = 'demo'; //username of the WordPress user account to impersonate
// get this username's ID
$user = get_user_by( 'login', $loginusername );
// only attempt to auto-login if at www.site.com/auto-login/ (i.e. www.site.com/?p=1234 ) and a user by that username was found
if (
! is_page( $loginpageid )
|| ! $user instanceof WP_User
) {
return;
}
$user_id = $user->ID;
// login as this user
wp_set_current_user( $user_id, $loginusername );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $loginusername, $user );
// redirect to home page after logging in (i.e. don't show content of www.site.com/?p=1234 )
wp_redirect( home_url() );
exit;
}
add_action( 'wp', 'auto_login', 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment