Exclude subscriber users from user list

I want to exclude Subscribers from a user list. My code is:

$users = $wpdb->get_results( "SELECT display_name FROM $wpdb->users ORDER BY display_name ASC" );

How can I change that so subscribers are excluded from the list?

Read More

I also looked at the get_users function in codex but it did not have an exclude by role parameter. 

Edit: Or another way would be to get the results filtered by capability (one that subscribers doesn’t have).

Related posts

3 comments

  1. $args = array(
        'role__not_in' => 'subscriber'
    );
    
    // The Query
    $user_query = new WP_User_Query( $args );
    
    // User Loop
    if ( ! empty( $user_query->results ) ) {
        foreach ( $user_query->results as $user ) {
            echo '<p>' . $user->display_name . '</p>';
        }
    } else {
        echo 'No users found.';
    }
    

    How about WP_User_Query with the role__not_in argument.

  2. This new method should work. It looks at all the capability values to find “subscriber”, and hides it.

    Try this query

    $wpdb->get_results(
        "SELECT display_name 
        FROM $wpdb->users 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 '%subscriber%') ORDER BY display_name ASC" 
    );
    
  3. You can use the get_users() function twice to exclude the subscribers.

    You can do something like this

    // Gets all the subscribers
    $user_query = get_users( array( 'role' => 'subscriber' ) );
    // This gets the array of ids of the subscribers
    $subscribers_id = wp_list_pluck( $user_query, 'ID' );
    // Now use the exclude parameter to exclude the subscribers
    $non_subscribers = get_users( array( 'exclude' => $subscribers_id ) );
    

    $non_subscribers contains the non subscribers.

    You can fetch the display_name by doing something like this

    foreach( $non_subscribers as $non_subscriber ) {
        echo $non_subscriber->display_name;
    }
    

Comments are closed.