Search code examples
phpwordpressfunctionhttp-redirectroles

Redirect by user role from a specific admin url to another url


This code works fine if I use is_front_page as current page/url, because it gets my homepage and redirects user by role to a specific path, but it doesn't work if I try to get a specific current url of wp admin dashboard, I tried with get_home_url(path), but it doesn't work:


add_action( 'template_redirect', 'role_based_redirect' );
function role_based_redirect() {
    if( get_home_url('/wp-admin/current-url') !== false ) { // this doesn't work
        $user = wp_get_current_user();
        if ( in_array( 'author', (array) $user->roles ) ) {
            wp_redirect( home_url( '/wp-admin/other-url' ) );
            exit;
        }
    }
}

Thank you in advance.


Solution

  • template_redirect hook is for front-side of your website. For admin side you can use different hooks. Such as init, admin_init etc.

    f.e.

    add_action( 'admin_init', 'role_based_redirect' );
    function role_based_redirect() {
        if( strpos($_SERVER["REQUEST_URI"],'wp-admin/current-url') !== false ) { 
            $user = wp_get_current_user();
            if ( in_array( 'author', (array) $user->roles ) ) {
                wp_redirect( home_url( '/wp-admin/other-url' ) );
                exit;
            }
        }
    }