skip to Main Content

I need to redirect user after registration to their author page.

The filter 'registration_redirect' is working, I just can’t seem to retrieve the recently registered user ID in order to get their author page and redirect them.

I am trying to get the recently registered user ID from $_POST, wp_get_current_user(), $_GET, however, no luck.

add_filter( 'registration_redirect', 'redirect_to_author_page' );
function redirect_to_author_page( $registration_redirect ) {
    
    // this is not working
    $user = wp_get_current_user(); 
    $user_id = $user->ID; // EMPTY
    
    // this is not working either
    $user = get_user_by( 'email', $_POST['user_email'] ); 
    $user_id = $user->ID; // EMPTY

    $author_url = get_author_posts_url( $user_id );

    return $author_url;
    
}

Any idea how could I retrieve the recently registered user ID in the ‘registration_redirect’ filter?
Any other way I could accomplish this? (Other filter or hook perhaps)?

Thank you

2

Answers


  1. If you check the documentation’s page for the registration_redirect filter, you’ll notice a second parameter called $errors.

    It’s not evident by its name, but, if the registration was successful, this parameter contains the user ID.

    So your code should look like this:

    add_filter( 'registration_redirect', 'redirect_to_author_page', 99, 2 );
    function redirect_to_author_page( $registration_redirect, $errors ) {
        // Use the default value if the registration wasn't successful
        if ( is_wp_error( $errors ) || ! isset( $errors ) ) {
            return $registration_redirect;
        }
    
        $user_id = $errors;
    
        $author_url = get_author_posts_url( $user_id );
    
        return $author_url;
    }
    
    Login or Signup to reply.
  2. An alternative hook to use is register_new_user as its specific to the wp-login.php form and receives the newly registered $user_id, eg:

    function redirect_to_author_page($user_id)
    {
        wp_safe_redirect(get_author_posts_url($user_id));
        exit();
    }
    
    add_action('register_new_user', 'redirect_to_author_page');
    

    Even though the documentation for registration_redirect states it should return $user_id on success, I tested and found it still contains WP_Error in WP 6.3 when called after a successful registration.

    Using register_new_user won’t interfere with the forms error handling; the redirection only occurs after a new user is successfully registered.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search