简体   繁体   中英

Redirect user after first login in 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.

You need to adjust your filter call like so;

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

在WordPress首次登录时重定向用户 :基于Cookie的解决方案和基于用户元表的解决方案

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM