Exclude Users of a Certain Role in the Users Page

class MyPlugin {

    public function __construct() {
        add_action('init', array(&$this, 'do_member_filter'));
    }

    public function do_member_filter() {
        $users = new WP_User_Query( array(
            'meta_query' => array(
                array(
                    'key'     => "{$GLOBALS['wpdb']->prefix}capabilities",
                    'value'   => 'abcrole',
                    'compare' => '!='
                )
            )
        ));


        do_action_ref_array('pre_user_query', $users);
    }
}

Related posts

1 comment

  1. How to use the class methods in the callback

    The $query object inside pre_user_query is a fully qualified core object, so you can use $query->set( 'key', 'value' ); as well as $query->get( 'key' );.

    If you got the problem that this might interfere with other callbacks, then simply add remove_filter( current_filter(), __FUNCTION__ ); to your callback, so it removes itself during the first call.

    Another way to go

    You can as well use those arguments directly when instantiating the class:

    $users = new WP_User_Query( array(
        'meta_query' => array(
            'relation'    => 'OR',
            array(
                'key'     => "{$GLOBALS['wpdb']->prefix}capabilities",
                'value'   => 'abcrole',
                'compare' => '!='
            ),
            array(
                'key'     => "{$GLOBALS['wpdb']->prefix}capabilities",
                'value'   => 'ab',
                'compare' => 'NOT LIKE'
            )
        )
    ) );
    

    Benefits

    This example shows how you can exclude users by a capability or role that matches exactly or is only named LIKE the role you’d like to exclude. This comes handy when you for example prefix some of your roles or capabilities and then want to mass-exclude them.

    You can as well just use the same in the callback. Pay attention that you use an array( array() ) for your meta query.

Comments are closed.