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? Commented Jul 12, 2013 at 8:13
  • I updated my answer Commented 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 Commented 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. Commented 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 ) Commented Feb 9, 2023 at 8:55

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.