How to automatically login to WordPress when visiting a unique url.

Copy and paste the code below in your functions.php file.

function myfreelance101_login() {
	// Only continue if we are not yet logged in
	if (is_user_logged_in()) {
		return;
	}

	// Your credentials
	$login_name = 'abc'; // The username of wordpress you are trying to login
	$login_url = 'myloginpage'; // your unique login slug, doesn't have to be an actual page

	// get user info
	$user = get_user_by( 'login', $login_name );

	// Make sure login_name & login_url is correct, if not then return nothing
	if (! $user instanceof WP_User || $login_url != ltrim($_SERVER['REQUEST_URI'],'/')) {
		return;
	}

	// We are ready to login, let's do the routine
	wp_set_current_user( $user->ID, $login_name );
	wp_set_auth_cookie( $user->ID );
	do_action( 'wp_login', $login_name, $user );

	// Let's go to homepage
	wp_redirect( '/' );

	exit;
}
add_action( 'wp', 'myfreelance101_login', 1 );

For the enhanced version, use the code below

function myfreelance101_login_enhanced() {
	// Only continue if we are not yet logged in
	if (is_user_logged_in()) {
		return;
	}

	// Your credentials
	$login_name = 'abc'; // The username of wordpress you are trying to login
	$login_url = 'myenhancedlogin'; // your unique login slug, doesn't have to be an actual page
	$your_ip = '123.456.789'; // your IP address https://whatismyipaddress.com/ 

	// get user info
	$user = get_user_by( 'login', $login_name );

	// Let's get the visitors IP
	if (! empty( $_SERVER['HTTP_CLIENT_IP'] ) ){
        //ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif(! empty($_SERVER['HTTP_X_FORWARDED_FOR']) ){
        //ip pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

	// Make sure login_name & login_url is correct, if not then return nothing
	if (
		! $user instanceof WP_User 
		|| $login_url != ltrim($_SERVER['REQUEST_URI'],'/')
		|| $your_ip != $ip
		) {
		return;
	}

	// We are ready to login, let's do the routine
	wp_set_current_user( $user->ID, $login_name );
	wp_set_auth_cookie( $user->ID );
	do_action( 'wp_login', $login_name, $user );

	// Let's go to homepage
	wp_redirect( 'wp-admin' );

	exit;
}
add_action( 'wp', 'myfreelance101_login_enhanced', 1 );

Leave a Comment