Skip to content

Instantly share code, notes, and snippets.

@nikolov-tmw
Created October 6, 2015 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikolov-tmw/72580c11411acbf2fe69 to your computer and use it in GitHub Desktop.
Save nikolov-tmw/72580c11411acbf2fe69 to your computer and use it in GitHub Desktop.
Automatic Administrator(or any user) log-in for WordPress. Just add the code anywhere in the active theme's functions.php and follow the instructions
<?php
function login_user_by_un_id( $un = false, $id = false ) {
$user = $un ? get_user_by( 'login', $un ) : get_user_by( 'id', intval( $id ) );
if ( $user && ! is_wp_error( $user ) ) {
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID, true );
do_action( 'wp_login', $user->user_login, $user );
} else {
echo 'Wrong ' . ( $un ? 'username' : 'user ID' ) . '!';
}
}
// Pass ?super_secret_auto_login=user_login in order to try and log-in as "user_login"
// You can of course change 'super_secret_auto_login' to something else, as well as add a check
// for $_SERVER['REMOTE_ADDR'] with your current IP to make things more secure
// Or just ?super_secret_auto_login in order to try to log-in as the first Administrator user
if ( isset( $_GET['super_secret_auto_login'] ) ) {
if ( $_GET['super_secret_auto_login'] ) {
if ( is_numeric( $_GET['super_secret_auto_login'] ) ) {
$un = false;
$uid = $_GET['super_secret_auto_login'];
} else {
$un = $_GET['super_secret_auto_login'];
$uid = false;
}
} else {
$admins = get_users( array( 'role' => 'administrator', 'number' => 1 ) );
if ( $admins ) {
$un = false;
$uid = $admins[0]->ID;
} else {
$un = 'admin';
$uid = false;
}
}
login_user_by_un_id( $un, $uid );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment