Skip to content

Instantly share code, notes, and snippets.

@jacks0n
Last active November 19, 2023 16:35
Show Gist options
  • Save jacks0n/743a45a98d74da23c8f2 to your computer and use it in GitHub Desktop.
Save jacks0n/743a45a98d74da23c8f2 to your computer and use it in GitHub Desktop.
Automatically login to WordPress, with a given user and optionally whitelist IPs. Add this to the bottom of wp-config.php, or your theme functions.php. To automatically login, visit the admin login page (/wp-login.php or /wp-admin/).
/**
* Automatically logs in a visitor when accessing the admin login area (/wp-login.php)
*
* @copyright Copyright (c) 2014, Jackson Cooper
* @license MIT
*
* Whitelist IPs: add IPs to whitelist in $ip_whitelist. If it is empty, it will allow all IPs.
* Username: Specify the username to login as with the "user" GET parameter (eg. ?user=admin).
* If the "user" get parameter is not set, $default_user_login will be used. If set
* to "*", it will login as the first administrator found. Otherwise it will use the
* value set.
*
* @note If already logged in, or just logged out, it will do nothing.
*/
function automatic_user_login() {
// Already logged in, not necessary
if (is_user_logged_in()) {
wp_redirect(admin_url());
return;
}
// IP whitelist. If this is empty, whitelisting will be disabled.
$ip_whitelist = array('127.0.0.1', '::1');
// Default user to login as.
// If this is "*", the first administrator user will be used.
// If the "user" GET parameter is set, this will be used.
$default_user_login = '*';
$ip_blocked = (!empty($ip_whitelist) and !in_array($_SERVER['REMOTE_ADDR'], $ip_whitelist));
$user_logged_out = (isset($_GET['loggedout']) and $_GET['loggedout'] === 'true');
if (($ip_blocked) // IP not whitelisted
or ($user_logged_out)) { // User just logged out
return;
}
// Fetch the user to login as, if it exists
$user_login = (isset($_GET['user'])) ? $_GET['user'] : $default_user_login;
if ($user_login === '*') {
$user = current(get_users(array('role' => 'administrator')));
if ($user === false) wp_die(__( 'ERROR: No admin users exist.'));
} else {
$user = get_user_by('login', $user_login);
if ($user === false) {
$admin_users = get_users(array('role' => 'administrator'));
$admin_users_atr = implode(', ', array_map(function($admin_user) {
return $admin_user->data->user_login;
}, $admin_users));
wp_die(__("ERROR: User '$user_login' does not exist. Other administrators: $admin_users_atr"));
}
}
// Login as $user and re-load / re-direct to the admin page
$user_id = $user->ID;
wp_set_current_user($user_id, $user->user_login);
wp_set_auth_cookie($user_id, true);
do_action('wp_login', $user->user_login);
wp_redirect(admin_url());
}
add_action('login_init', 'automatic_user_login');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment