Search code examples
phpwordpresshttp-redirectbuddypress

Attempting to Redirect to User Profile


Using BuddyPress, I am attempting to redirect all registered users to their user profile; however when redirecting the resulting URL is not including the user_login... as a result every user is redirecting to "domain/members/".

How can I get the username to show up in the URL to then redirect to the following: "domain/members/username/"?

FUNCTIONS.PHP

add_filter('login_redirect', function ($redirect_to, $request, $user){
    if (user_can($user, 'registered')){
      $current_user = wp_get_current_user();
      return '/members/' . $current_user->user_login . '/';
    }
}

Solution

  • As stated in the WordPress Codex: "The $current_user global may not be available at the time this filter is run. So you should use the $user global or the $user parameter passed to this filter."

    https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect

    add_filter('login_redirect', function ($redirect_to, $request, $user){
        if (user_can($user, 'registered')){
            return bp_core_get_user_domain( $user->ID );
        }
    }