WordPress User Login Redirect

WordPress sites that offer personalized or private content typically want to keep their users on the front end of the site.  However, WordPress automatically takes users to the back end dashboard after they login.  Obviously, we need to be able to redirect these users to the front end of the site; but at the same time, anyone who is an admin will probably still want to end up on the back end of the site. WordPress gives us the ability to edit where users are sent after they login by using the login_redirect filter.

The code snippet below will allow you to easily detect the user’s role and redirect them to the appropriate location:

<?php 

/**
 * 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 );

Note that the has_cap() method in the code above will check if a user has a specific role or capability.  Additionally, the home_url() function will take a slug or relative path and can also be replaced with get_permalink() if you prefer to pass in a specific page or post id.

Another possibility is to redirect a WordPress user on login based on custom user meta:

<?php

/**
 * 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 );

One great possible use of the code above would be localization. For example, lets say that you have a restaurant with five locations. When a user logs in to your website, they can place their lunch order at their favorite location. If you were to simply store their favorite location as custom user meta, then you could check that data when they login and automatically send them to the correct order page.

https://wpscholar.com/blog/wordpress-user-login-redirect/
«
»
ACF (3)
Admin Column (4)
Breadcrumbs (2)
CSS (6)
Custom post types (4)
Custom Taxonomies (3)
Customizer (4)
Hooks & Filters (3)
Jquery (9)
LAMP (10)
Login (5)
Meta boxes (6)
Multisite (2)
My Code (1)
Open Graph Meta Tags (1)
Redirects (2)
SEO (4)
Theme Building (5)
Title Tags (2)
Typography (3)
Uncategorised (54)
User Roles & Capabilities (2)
White labeling (9)
Working with Images (11)
Working with videos (2)
WP Database (1)