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 badge1 Answer
Reset to default 1If 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...
版权声明:本文标题:functions - How to show only specific category post by user role without plugin and restrict all other cats 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745234533a2648974.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论