Skip to content

Instantly share code, notes, and snippets.

@faceonline
Forked from cliffordp/functions.php
Last active January 15, 2024 05:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save faceonline/7a36f4f2ceea4c28ab47b88af942017f to your computer and use it in GitHub Desktop.
Save faceonline/7a36f4f2ceea4c28ab47b88af942017f to your computer and use it in GitHub Desktop.
Automatically login a single WordPress user upon arrival to a specific page. Redirect to home page once logged in. Prevent viewing the login page. Tested with WP 3.9.1. Used in functions.php
<?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.
//Tested with WP 3.9.1. Used in functions.php
//Updated 2014-07-18 to resolve WP_DEBUG notice: "get_userdatabylogin is deprecated since version 3.3! Use get_user_by('login') instead."
//From http://tourkick.com/2014/wordpress-demo-multisite-db-reset/
function auto_login() {
//change these 2 items
$loginpageid = '1234'; //Page ID of your login page
$loginusername = 'demo'; //username of the WordPress user account to impersonate
if (!is_user_logged_in()
&& is_page($loginpageid)) { //only attempt to auto-login if at www.site.com/auto-login/ (i.e. www.site.com/?p=1234 )
//get user's ID
$user = get_user_by('login', $loginusername);
$user_id = $user->ID;
//login
wp_set_current_user($user_id, $loginusername);
wp_set_auth_cookie($user_id);
do_action('wp_login', $loginusername);
//redirect to home page after logging in (i.e. don't show content of www.site.com/?p=1234 )
wp_redirect( home_url() );
exit;
} else {
if(is_page($loginpageid)) {
//prevent viewing of login page even if logged in
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