Home > Software engineering >  Redirect user to a personal page based on User Id
Redirect user to a personal page based on User Id

Time:07-21

Hi I use this code to redirect users on login based on the user role.

I want to modify it to use redirect based on the user id.

How could i do this? Thanks

function my_login_redirect( $url, $request, $user ){
if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
    if( $user->has_cap( 'administrator' ) ) {
        $url = home_url('mypage.html');
        } else {
            $url = home_url('/index.php');
            }
            }
            return $url;}add_filter('login_redirect', 'my_login_redirect', 10, 3 );

CodePudding user response:

Your $user object already contains the ID.

Your code would then look like this if you want to check for user with id 79:

function my_login_redirect( $url, $request, $user ){
    if ( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
        if ( $user->ID == 79 ) {
            $url = home_url( '/mypage.html' );
        } else {
            $url = home_url( '/index.php' );
        }
    }
    return $url;
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

Put the above in your functions.php. Tested and works.

  • Related