Code Snippet to Redirect Users Based on Their Role in WordPress

Marek K. Jan 12, 2025 User Management
How can I send different types of users to different pages on my WordPress site?
What PHP code can I use to create a user role-based redirect in WordPress, ensuring that users are directed to specific pages based on their roles?
Andy answered Jan 12, 2025

Role-Based Redirect Solution

Custom Code Solution

This code redirects users to different pages based on their roles when they log in. Place this code in your theme's functions.php file or in a site-specific plugin:

function redirect_users_by_role($user_login, $user) {
    // Get user's first role
    $user_role = $user->roles[0];
    
    // Define redirect URLs for different roles
    $redirect_urls = array(
        'administrator' => '/admin-dashboard',
        'editor'       => '/editor-page',
        'subscriber'   => '/member-area',
        // Add more roles and URLs as needed
    );
    
    // Check if role exists in our array
    if (isset($redirect_urls[$user_role])) {
        wp_safe_redirect(home_url($redirect_urls[$user_role]));
        exit();
    }
}
add_action('wp_login', 'redirect_users_by_role', 10, 2);

Alternative method using template_redirect hook to redirect users on any page load:

function redirect_logged_in_users() {
    if (!is_user_logged_in()) {
        return;
    }
    
    $user = wp_get_current_user();
    $role = $user->roles[0];
    
    // Define restricted pages and their allowed roles
    $page_permissions = array(
        '/members-only' => array('subscriber', 'editor', 'administrator'),
        '/editors-area' => array('editor', 'administrator'),
        '/admin-only'   => array('administrator')
    );
    
    // Get current page path
    $current_path = $_SERVER['REQUEST_URI'];
    
    // Check if current page is restricted
    foreach ($page_permissions as $page => $allowed_roles) {
        if (strpos($current_path, $page) !== false && !in_array($role, $allowed_roles)) {
            wp_safe_redirect(home_url());
            exit();
        }
    }
}
add_action('template_redirect', 'redirect_logged_in_users');

Plugin Solutions

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

  1. Peter's Login Redirect

    • Allows setting up role-specific redirects
    • Includes URL-specific redirections
    • Simple interface
  2. Redirect Users by Role

    • Dedicated to role-based redirections
    • Clean admin interface
    • Supports multiple redirect rules

Additional Notes

  • For the custom code solution, modify the $redirect_urls array to match your site's URL structure
  • Use full URLs if redirecting to external sites
  • Test redirects in incognito mode to avoid caching issues
  • Consider adding role checks if certain pages should be restricted
  • Always use wp_safe_redirect() instead of PHP's header() for security