Redirect user after first login in wordpress?

2019-03-16 08:58发布

问题:

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.

回答1:

You need to adjust your filter call like so;

// filter name, callback, priority, accepted args
add_filter('login_redirect', 'mylogin_redirect', 10, 3);


回答2:

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



标签: wordpress