Implement a custom redirect for users based on their roles after they log in

Mike D Dec 18, 2024 User Redirects
How can I send different users to different pages when they log into my website?
What is the custom PHP code to implement role-based redirects for users after login in WordPress?
Andy answered Dec 18, 2024

Role-Based Login Redirects in WordPress

Custom Code Solution

Add this code to your theme's functions.php file or in a site-specific plugin:

This code hooks into WordPress login process and redirects users based on their role:

function custom_login_redirect($redirect_to, $request, $user) {
    if (!is_wp_error($user)) {
        // Get user's first role
        $role = $user->roles[0];
        
        // Define redirect URLs for different roles
        $redirect_targets = array(
            'administrator' => '/wp-admin/',
            'editor'       => '/editor-dashboard/',
            'author'       => '/author-area/',
            'subscriber'   => '/member-homepage/',
            // Add more roles and URLs as needed
        );
        
        // Check if role exists in our array
        if (array_key_exists($role, $redirect_targets)) {
            return home_url($redirect_targets[$role]);
        }
    }
    
    // Default redirect if no match
    return $redirect_to;
}
add_filter('login_redirect', 'custom_login_redirect', 10, 3);

For more specific control over login redirects, including custom conditions:

function advanced_login_redirect($redirect_to, $request, $user) {
    if (!is_wp_error($user)) {
        // Check for specific user ID
        if ($user->ID == 123) {
            return home_url('/special-page/');
        }
        
        // Check for specific role with additional conditions
        if (in_array('subscriber', $user->roles)) {
            // Example: check user meta
            $access_level = get_user_meta($user->ID, 'access_level', true);
            if ($access_level == 'premium') {
                return home_url('/premium-area/');
            }
            return home_url('/basic-area/');
        }
    }
    
    return $redirect_to;
}
add_filter('login_redirect', 'advanced_login_redirect', 10, 3);

Plugin Solutions

If you prefer using a plugin, here are reliable options:

  1. Peter's Login Redirect

    • Offers role-based redirects
    • Supports URL variables
    • Includes conditional logic
  2. Profile Builder

    • Advanced user management
    • Custom redirects
    • User role editor

Important Notes

  • Test redirects thoroughly in private browsing mode
  • Ensure redirect URLs exist and are accessible
  • Consider redirect loops when setting URLs
  • Use home_url() function for proper URL formatting
  • Maintain security by validating user permissions

The custom code solution is lightweight and easily customizable. Adjust the redirect URLs in the $redirect_targets array to match your site's structure.