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…