0

I've two roles,

  1. Members
  2. Recruiter.

Both will post in Custom Post type "Companies".
When they about to edit/delete their own posts, I don't want them to see other posts posted by other roles. At present it is displaying title of other role's posts in the backend. Roles cannot edit/delete other role in the backend but I'm seeing other roles posts title by view link.

How do get rid of it?

Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97
Shoeb Mirza
  • 912
  • 1
  • 11
  • 30

1 Answers1

0

You can achieve this by using parse_query filter with $pagenow global variable.

  1. Get the logged in user role.
  2. Then get all the User ID with that role
  3. 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

Community
  • 1
  • 1
Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97