0

I have a simple requirement, after user login set the login user session and then redirect to another page.

Yes, I found some similar page from here is-there-a-hook-that-runs-after-a-user-logs-in

As the post said, what I need to do is like this:

function set_blog_session(){
    $_SESSION['blogger'] = get_current_user_id();
    wp_redirect("http://www.google.com");//just for test
}
add_action('wp_login', 'set_blog_session');

But I got nothing.

First, get_current-user_id() always returns 0.
Second, no redirect at all.

Whats going wrong?

1 Answer 1

2

You should use exit after using the wp_redirect():

From the Codex:

wp_redirect() does not exit automatically and should almost always be followed by exit.


For your hook, you could pass a parameter in your callback function to get the user login and then use get_user_by() to get the ID.

function set_blog_session($user_login){
    $user_obj = get_user_by('login', $user_login );
    $_SESSION['blogger'] = $user_obj->ID;

    wp_redirect("http://www.google.com");
    exit;
}
add_action('wp_login', 'set_blog_session');
5
  • thanks man, yes, need to be add exit. And what's wrong with my first problem, why get_current_user_id() got 0?
    – diligent
    Jul 12, 2013 at 8:13
  • I updated my answer
    – RRikesh
    Jul 12, 2013 at 8:17
  • it works man, but I wonder, why use get_current_user_id() not working, because I have been logon, so it should be get the current user id ? Thanks
    – diligent
    Jul 12, 2013 at 8:28
  • I don't know why get_current_user_id() doesn't work, maybe someone else will help us understand that point.
    – RRikesh
    Jul 12, 2013 at 9:19
  • Shouldn't have to call get_current_user_id, the hook passes the $WP_User object: do_action( 'wp_login', string $user_login, WP_User $user ) Feb 9, 2023 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.