Last updated on September 14, 2023

Hide Pages from User Role

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Hide pages from a specific user role.

To hide specific pages from a user based on their user role in WordPress, you can use the template_redirect action hook to redirect them to another page or display a custom message. Here’s an example of how you can achieve this:

function wpsnippets_hide_pages_from_user_role() {
    $user = wp_get_current_user();
    $allowed_roles = array( 'editor', 'author' ); // Array of allowed user roles
    $restricted_pages = array( 'page1', 'page2', 'page3' ) ;

    if ( array_intersect( $allowed_roles, $user->roles ) && is_page( $restricted_pages ) ) {
        wp_safe_redirect( home_url() ); // Redirect to the home page
        exit;
    }
}

add_action( 'template_redirect', 'wpsnippets_hide_pages_from_user_role' );

In this example, $allowed_roles is an array of user roles that are allowed to access the specified pages. You can replace 'editor' and 'author' with the roles you want to allow.

Inside the wpsnippets_hide_pages_from_user_role() function, wp_get_current_user() retrieves the current user’s information, and array_intersect() is used to check if any of the user’s roles intersect with the $allowed_roles array. The is_page() function is used to check if the current page matches the specified slugs or IDs. If both conditions are met, the user is redirected to the home page using wp_safe_redirect(), and exit is called to terminate further execution.

By adding this code snippet to your WordPress site, you can hide specific pages from users who do not have the allowed user role. When users with the allowed roles try to access those pages, they will be redirected to the home page or any other URL you specify in wp_redirect().

Last updated on September 14, 2023. Originally posted on May 19, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *