Categories
Local SEO PHP SEO Social Media Marketing Technology Wordpress

WordPress Redirect a user on first login

Suppose you have some information you want to direct first time users to, such as a term and condition  page, or a list of certain posts, etc. You would like to do that the first time they login as a new user.  You can do that with the below code . In this example, I will show you how to redirect the user to the specific page if it is the first time they have logged in.

Add the below code in functions.php of your active theme, or a custom plugin. or You can download the plugin from wordpress directory .

//hook when user registers
add_action( ‘user_register’, ‘myplugin_registration_save’, 10, 1 );

function myplugin_registration_save( $user_id ) {

// insert meta that user not logged in first time
update_user_meta($user_id, ‘prefix_first_login’, ‘1’);

}

// hook when user logs in
add_action(‘wp_login’, ‘your_function’, 10, 2);

function your_function($user_login, $user) {

$user_id = $user->ID;
// getting prev. saved meta
$first_login = get_user_meta($user_id, ‘prefix_first_login’, true);
// if first time login
if( $first_login == ‘1’ ) {
// update meta after first login
update_user_meta($user_id, ‘prefix_first_login’, ‘0’);
// redirect to given URL
wp_redirect( ‘http://www.example.com/’ );
exit;
}

Leave a Reply

Your email address will not be published. Required fields are marked *