I am using basic post for adding posts. 5 categories exist ( cat_A, cat_B, cat_C, cat_D, cat_E). And I have 2 custom user_role for registered visitors that is 'viewer_a' and 'viewer_b'. I need to show only selected category post only for specific user roles.

So, users under 'viewer_a' can view only cat_A posts and under user_role 'viewer_B' can view cat_B posts only. Strictly restrict other posts.

How can I do that without plugin?


If you're using global loop for displaying the posts, then you can easily modify which posts are shown using pre_get_posts action.

function restrict_categories_for_user( $query ) {
    if ( ! is_admin() && $query->is_main_query() && get_current_user_id() ) {
        $user = wp_get_current_user();
        if ( in_array( 'viewer_a', (array) $user->roles ) ) {
            // The user has the "viewer_a" role
            $query->set( 'category_name', 'cat_A' );  // <- use category slug here
        if ( in_array( 'viewer_b', (array) $user->roles ) ) {
            // The user has the "viewer_b" role
            $query->set( 'category_name', 'cat_B' );  // <- use category slug here
add_action( 'pre_get_posts', 'restrict_categories_for_user' );

I assume that you want to restrict which posts can be viewed by these users on front-end. If you want to restrict posts visible in back-end, then you'll have to change this condition if ( ! is_admin() && $query->is_main_query() && get_current_user_id() ) { accordingly...

  • user automatically redirecting to specific category posts, but the post_type "viewer_a" users can view the category post of post_type "viewers_b" posts if they copy the post url. there is no restriction. how can i restrict other category. user can view only the specific cat post. thanks for your answer. kindly update – sasa Aug 18 '19 at 17:52
  • front end restriction – sasa Aug 18 '19 at 17:54

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.