Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide users with a specific role from users list on WordPress admin dashboard

I have two roles called Agent and Subagent. I want to hide these two specific roles from the admin user list.

I tried using the pre_user_query filter but couldn't get it to work.

Could anyone please suggest a correct way to do it?

Thanks,

like image 663
Rakhi Prajapati Avatar asked Dec 24 '22 05:12

Rakhi Prajapati


2 Answers

Simpler & safer:

add_filter('pre_get_users', function ($user_query) {
  // use the sluglike role names, not their "display_name"s 
  $user_query->set('role__not_in', ['agent', 'subagent']);
});

role__not_in available since WP 4.4.

Caveat: the roles (and their user count) will still show up above the users table.

like image 173
kubi Avatar answered Dec 29 '22 00:12

kubi


I found the perfect solution for what I wanted here: https://rudrastyh.com/wordpress/pre_user_query.html

add_action('pre_user_query','hide_all_agents_subagents');

function hide_all_agents_subagents( $u_query ) {
    
    $current_user = wp_get_current_user();
    if ( $current_user->roles[0] != 'administrator' ) { 
        global $wpdb;
        $u_query->query_where = str_replace(
            'WHERE 1=1', 
            "WHERE 1=1 AND {$wpdb->users}.ID IN (
                SELECT {$wpdb->usermeta}.user_id FROM $wpdb->usermeta 
                    WHERE {$wpdb->usermeta}.meta_key = '{$wpdb->prefix}capabilities'
                    AND {$wpdb->usermeta}.meta_value NOT LIKE '%agent%' AND {$wpdb->usermeta}.meta_value NOT LIKE '%subagent%')", 
            $u_query->query_where
        );
    }
}
like image 25
Rakhi Prajapati Avatar answered Dec 28 '22 23:12

Rakhi Prajapati