Home > database >  Wordpress redirect based on user role and specific page ID
Wordpress redirect based on user role and specific page ID

Time:10-03

I'm trying to create a function for a WordPress site that basically says, if the user has a role called LinkedIn and tries to access any page that is not page ID #6, then I need to redirect them to a different page.

Here is my code below, but it doesn't work and I cant figure out why... what am I missing?


add_action('template_redirect', 'redirect_user_role');  
function redirect_user_role() {      
    $user = wp_get_current_user();
if ( in_array( 'linkedin', (array) $user->roles ) ) {
    if(!is_page( 6 ))   {           
        wp_redirect('/no-access/');     
    } 
}
}

And how my custom role is registered:

add_role( 'linkedin', __( 'LinkedIn' ), array( 'read' => true, ) ); 

Your help is so appreciated!

CodePudding user response:

You have to add exit after using wp_redirect. https://developer.wordpress.org/reference/functions/wp_redirect/

add_action('template_redirect', 'redirect_user_role');
function redirect_user_role() {
    $user = wp_get_current_user();
    if ( in_array( 'linkedin', (array) $user->roles ) ) {
        if(!is_page( 6 ))   {
            wp_redirect('/no-access/');
            exit();
        }
    }
}
  • Related