Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect user after first login in wordpress?

Tags:

wordpress

This code checks if a user is logging in for the first time, that is after registration. I want to redirect him to a custom page if so. Otherwise, redirect him to the homepage or admin page.

 function mylogin_redirect() {
    global $user_ID;
    if( $user_ID ) {
        $user_info = get_userdata( $user_ID ); 
        // If user_registered date/time is less than 48hrs from now
        // Message will show for 48hrs after registration
        if ( strtotime( $user_info->user_registered ) > ( time() - 172800 ) ) {
            header("Location: http://example.com/custompage");
        } elseif( current_user_can( 'manage_options' )) {
            header("Location: http://example.com/wp-admin/");
        } else {
            header("Location: http://example.com/");
        }
    }
}
add_action('wp_head', 'mylogin_redirect');

But it doesn't work? My guess is it doesn't get hooked into wp_head... I tried the following using login_redirect filter:

 function mylogin_redirect($redirect_to, $url_redirect_to = '', $user = null) {
    global $user_ID;
    if( $user_ID ) {
        $user_info = get_userdata( $user_ID ); 
        // If user_registered date/time is less than 48hrs from now
        // Message will show for 48hrs after registration
        if ( strtotime( $user_info->user_registered ) > ( time() - 172800 ) ) {
            return get_bloginfo('url') . "/custompage/";
        } elseif( current_user_can( 'manage_options' )) {
            return admin_url();
        } else {
            return get_bloginfo('url');
        }
    }
}
add_filter('login_redirect', 'mylogin_redirect');

Though it logs me in, it doesn't get me anywhere but to http://example.com/wp-login.php instead with a blank page.

UPDATE: Ok, I don't know what's happening. Using the filter hook, I can get to the intended destination only after second login. Well not really second login but on the second click of the login button. I did it like so: enter credentials -> login -> (wrong page) -> hit back button -> enter credentials again -> login -> (correct page). Weird.

like image 681
Joann Avatar asked Nov 24 '10 13:11

Joann


People also ask

How do I redirect a user to a page after login?

The most common ways to implement redirection logic after login are: using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL.


Video Answer


2 Answers

You need to adjust your filter call like so;

// filter name, callback, priority, accepted args
add_filter('login_redirect', 'mylogin_redirect', 10, 3);
like image 189
TheDeadMedic Avatar answered Sep 27 '22 23:09

TheDeadMedic


Redirecting users on first login in WordPress: Cookie-based solution & User meta table based solution

like image 28
tiaurus Avatar answered Sep 27 '22 23:09

tiaurus