admin管理员组

文章数量:1415484

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?

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?

Share Improve this question edited Aug 18, 2019 at 11:15 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Aug 17, 2019 at 18:16 sasasasa 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

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...

本文标签: functionsHow to show only specific category post by user role without plugin and restrict all other cats