0

I am creating a website that consists of a "Home Page" (public) that has a login link to the WP login page, then, there will be different pages that are only accessible to specific logged members depending on their user roles. For example, home page (public), Page 1 (role x), Page 2 & 3 & 4 (role Y), Page 5&6 (Role 3). Is there a method/plugin to match different WP pages to specific user roles? Also, I know some basic coding, so I can use PHP snippets (with your help) if this is the only way to resolve this.

Best regards, Geo

0

Don't know if there is plugin for this or not, you should try by searching "restrict page by user roles" in WordPress directory. But if you can code and know few conditional tags and how to use them then I think you should try following snippet and it will work for you.

But Beware, this will redirect to home for all the other page you not entered in $allowed_pages array. So just add more if conditions as per your requirements.

add_action( 'template_redirect', 'neo_restrict_pages_as_per_user_roles' );
function neo_restrict_pages_as_per_user_roles(){
    if( is_user_logged_in() && !current_user_can('administrator') && (!is_home() || !is_front_page() ) ){
        $user_meta = wp_get_current_user();
        $user_roles=$user_meta->roles;

        $allowed_pages = array(
                                'subscriber' => array('2'),
                                'author' => array('16','18')
                            );

        if( array_key_exists($user_roles[0], $allowed_pages) ){
            $allowed_pages_ids = $allowed_pages[$user_roles[0]];
            if( !in_array( get_the_ID(), $allowed_pages_ids ) ){
                wp_redirect( home_url(), 302 );
            }
        }
    }
}

in above code you just have to add page ids in following array along with their roles

$allowed_pages = array(
    'subscriber' => array('2'),
    'author' => array('16','18')
    // user roles => array('page id 1', 'page id 2', ...)                       
);

put this in you functions.php file in theme, but before doing that don't forgot to take backup of that file. so that if not work as per your requirement you can revert it back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.