WordPress

Effective WordPress User Login Redirect: Maximize User Experience and Engagement

WordPress sites that provide personalized or private content often seek to keep users on the site’s front end. However, after logging in, WordPress immediately redirects users to the back end dashboard. Obviously, we need to be able to redirect these people to the front end of the site; however, any admin will most likely want to end up on the back end of the site. Using the login_redirect filter, we can change where users are directed when they log in.

The following code snippet will allow you to quickly determine the user’s role and redirect them to the correct location:

/**
 * WordPress function for redirecting users on login based on user role
 */
function my_login_redirect( $url, $request, $user ){
    if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
        if( $user->has_cap( 'administrator' ) ) {
            $url = admin_url();
        } else {
            $url = home_url('/members-only/');
        }
    }
    return $url;
}

add_filter('login_redirect', 'my_login_redirect', 10, 3 );

The has_cap() method in the above code checks to see if a user has a specified role or capacity. Furthermore, the home_url() method accepts a slug or relative path and may be changed with get_permalink() if you wish to give a specific page or post id.

Another option is to reroute a WordPress user when he or she logs in depending on custom user meta:

/**
 * WordPress function for redirecting users based on custom user meta
 */
function my_login_redirect( $url, $request, $user ){
    if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
        if( 'cool' == get_user_meta( $user->ID, '_is_cool', true ) ) {
            $url = home_url('/cool-people-only/');
        }
    }
    return $url;
}

add_filter('login_redirect', 'my_login_redirect', 10, 3 );

Localization is one wonderful application for the code above. For example, suppose you own a restaurant with five locations. When a person joins in to your website, they may make an order for lunch at their preferred location. If you just saved their preferred location as custom user meta, you could verify that data when they logged in and immediately redirect them to the relevant order page.

Leave a Reply

Your email address will not be published. Required fields are marked *