如果使用全局循环来显示帖子,那么可以使用pre_get_posts
行动
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\' );
我假设您想限制这些用户可以在前端查看哪些帖子。如果要限制在后端可见的帖子,则必须更改此条件
if ( ! is_admin() && $query->is_main_query() && get_current_user_id() ) {
照着