redirect the user to my custom template when the user logs in for the first time only

Context: redirect the user to my custom template when the user logs in for the first time only

Solution: It is possible to do so. We can use two action hooks, user_register and wp_login to implement this little tricks. wp_signon authenticates a user with option to remember credentials. Replaces deprecated function wp_login.

Whenever a new user is created, this function will add a custom field with value 1.

function sasweb_new_user($user_id) { 
   add_user_meta( $user_id, '_new_user', '1' );
}
add_action( 'user_register', 'sasweb_new_user');

The next function will check if user logs in for the first time and redirect the user.This function can be customized to serve your needs.

 sasweb_check_login_redirect($user_login, $user) {
   $logincontrol = get_user_meta($user->ID, '_new_user', 'TRUE');
   if ( $logincontrol ) {
      //set the user to old
      update_user_meta( $user->ID, '_new_user', '0' );

      //Do the redirects or whatever you need to do for the first login
      wp_redirect( 'http://www.example.com', 302 ); 
exit;
   }
}
add_action('wp_login', 'sasweb_check_login_redirect', 10, 2);

The function sasweb_check_login_redirect knows the user. We can display custom welcome message or display users data on screen.

About the Author

dr.code.skm

I am backend developer with passion in Web Application development using latest technologies like Laravel, PHP7, React, ECMAScript 6 and WordPress. I prefer spending time analyzing big data with Apache Spark. Apart from that, I do photography.