Search code examples
wordpresswordpress-admin

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,


Solution

  • 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
            );
        }
    }