How to auto log-in users that click on links in your email campaigns

Use the PHP code snippet below to auto-login users who click on links in your email campaigns.

This is useful, for example, when sending an abandoned cart email series or custom magic login links.

<?php
add_filter( 'noptin_actions_page_template', 'noptin_custom_code_autologin_user', 0 );
function noptin_custom_code_autologin_user( $template ) {
	$handler = noptin()->actions_page;

	// Check if a guest has clicked a link in a previous email.
	if ( 'email_click' === $handler->get_request_action() && 0 === get_current_user_id() ) {

		// Decode the recipient details.
		$recipient = $handler->get_request_recipient();

		// If we have a user id, log them in.
		if ( ! empty( $recipient['email'] ) ) {
			$user = get_user_by( 'email', $recipient['email'] );
		}

		if ( empty( $user ) && ! empty( $recipient['uid'] ) ) {
			$user = get_user_by( 'id', $recipient['uid'] );
		}

		if ( ! empty( $user ) ) {
			wp_set_current_user( $user->ID );
			wp_set_auth_cookie( $user->ID, true );
			do_action( 'wp_login', $user->user_login, $user );
		}
	}

	return $template;
}

Tip: Add this code snippet to your theme’s functions.php file or use the code snippets plugin.

Code Explanation

  • Line 2: Registers a filter hook that’s called whenever someone opens the Noptin actions page.
  • Line 7: Ensures the current action is a click event and that the user who took the action is not logged in.
  • Line 10: Decodes the current recipient details.
  • Line 21: Logs in the current recipient if their details match an existing user.

Up your Marketing
Join our email list to and we'll send you occasional marketing tips
Custom CSS Slide Example
Custom Animation Example
Default Animation