• The only forum and blog entries out there I have found that don’t use SQL to get a list of users with a specific role, use WP_User_Search. This is all well and good, but that function is specifically for use in a paginated list.

    This is my ‘hack’ for getting ‘all’ of my users (of my new custom type):

    function get_pianists(){
      require_once( ABSPATH . '/wp-admin/includes/user.php' );
      $wp_user_search = new WP_User_Search(  '', '', 'pianists');
      $wp_user_search->users_per_page = 1000;
      $wp_user_search->prepare_query();
      $wp_user_search->query_sort = ' ORDER BY display_name';
      $wp_user_search->query();
      $wp_user_search->prepare_vars_for_template_usage();
      $wp_user_search->do_paging();
      return $wp_user_search->get_results();
    }

    Is there a better way? Or is this something worth working out a patch for?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The better way IS to use a SQL query ??
    It would also be faster and involves less overhead. What you’re doing currently is simply calling functions to help put together the SQL query which is what finds all your users anyway.

    Thread Starter miradev

    (@miradev)

    There 2 reasons not to do this.

    1. Prominent WP developers and contributors recommend that you do not do it.
    2. It makes for really ugly SQL, mainly because the role is stored in a piece of serialised js

    Imagine I have 2 groups of users: ‘artist’ and ‘recording_artist’. To find just the artists I will need this:

    "SELECT ID FROM {$wpdb->users} u JOIN {$wpdb->usermeta} um ON um.user_id = u.ID WHERE um.meta_key = '{$wpdb->prefix}capabilities' AND um.meta_value = 'a:1:{s:6:\"artist\";b:1;}'";

    If I use LIKE ‘%artist%’ then I get both user roles.

    So at the moment, I really don’t see a good solution.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Get all users with a specific role’ is closed to new replies.