Puddinq.com sharing knowledge

Autologin for wordpress

Autologin for wordpress

At one site I have a custom role that can only view the orders. The owner wants some users to hav access without a password. Yes this story gets dumber.. He wants to give access by clicking a link.

The basic script offered to autologin are hooked in to ‘plugins_loaded’ or ‘wp’. Both these hooks resulted in white screens.. WooCommerce did not like the usercapabilities to switch.

The solution was the ‘init’ hook.

// auto login

function auto_login() {
	//change these 2 items
	$login_request = isset($_GET['code']) ? $_GET['code'] : '';
	$login_key = 'KKGFJ96DKGHJ979679KJHGK098MGHJGKKG'; //Page ID of your login page
	$loginusername = 'the user nam'; //username of the WordPress user account to impersonate
	if (!is_user_logged_in() && $login_request == $login_key) { //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;
		wp_set_current_user($user_id, $loginusername);
		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( $_SERVER['REQUEST_URI'] );
add_action('init', 'auto_login');

By adding ?code=KKGFJ96DKGHJ979679KJHGK098MGHJGKKG to any url the users gets loged in. You can even use https://www.example-domain.nl/wp-admin/edit.php?code=KKGFJ96DKGHJ979679KJHGK098MGHJGKKG&post_type=shop_order and the user gets redirected to the order page. ( now the link gives access ).