You can achieve this by using parse_query
filter with
$pagenow
global variable.
- Get the logged in user role.
- Then get all the User ID with that role
- Pass those ID through
author__in
key.
Here is the code
add_filter('parse_query', 'wh_hideOthersRolePost');
function wh_hideOthersRolePost($query) {
global $pagenow;
global $current_user;
$my_custom_post_type = 'companies'; // <-- replace it with your post_type slug
$my_custom_role = ['members', 'recruiter']; // <-- replace it with your role slug
//if user is not logged in or the logged in user is admin then dont do anything
if (!is_user_logged_in() && !is_admin())
return;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if(!in_array($user_role, $my_custom_role))
return;
$user_args = [
'role' => $user_role,
'fields ' => 'ID'
];
//getting all the user_id with the specific role.
$users = get_users($user_args);
//print_r($users);
if (!count($users)) {
return;
}
$author__in = []; // <- variable to store all User ID with specific role
foreach ($users as $user) {
$author__in[] = $user->ID;
}
if (is_admin() && $pagenow == 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] == $my_custom_post_type){
//retriving post from specific authors which has the above mentioned role.
$query->query_vars['author__in'] = $author__in;
}
}
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Code is tested and works.
Hope this helps!
Some what related question: Hide "free" orders in WooCommerce orders section from admin panel