WP Smith

Creating WordPress & Genesis Websites Since 2010

  • Home
  • About
  • Services
  • Blog
  • Contact

Aug 16 2012

An Introduction to WP_User_Query Class

Recently, I created this argument guide for WP_User_Query Class, similar to the existing WP_Query Class guide by Mark Luetke.

Some Basic Examples

Here's a basic usage example:

Here's a basic usage example for all users except authors:

Here's a basic usage example for all users except editors and administrators:

Modifying the Query

However, there is more to this than the basic query, just like WP_Query. Once the query has been prepared, you can easily access the query via pre_user_query hook. However, unlike WP_Query, by default, there is no way (no method like WP_Query::is_main_query()) to distinguish between user queries with WP_User_Query as one would do on pre_get_posts.

So for a complicated example: if we want to query users, control which query we change, and order (say) by the last name user meta field or some other user meta, we are stuck with two basic approaches to modifying the query and only the query you wish to modify.

Approach #1 (Not the best IMHO)

First, you could modify the query directly through the WP_User_Query object. Though the PHP docs claims that WP_User_Query::query() is a private function, it really isn't. So you can do something like this:

Please note the Caveat: This creates 2 queries and any use of this code should also use site transients.

Basically this code, makes one query, with the original arguments. Then we modify the query arguments in the object and the re-execute the query method, by-passing the sanitizing prepare method. Going this route could drastically hurt your site both in performance and simply breaking the site.

Side Note: $author_query = new WP_User_Query(); doesn't actually prepare or run the query. It creates an object that looks like this:

WP_User_Query Object
(
    [results] =>
    [total_users] => 0
    [query_fields] =>
    [query_from] =>
    [query_where] =>
    [query_orderby] =>
    [query_limit] =>
)

Approach #2 (The better approach)

Second (and by far the better way), you can add an identifier argument (here: query_id), which WordPress retains as a query_var.

WP_User_Query Public Methods

WP_User_Query has two declared public methods: WP_User_Query::get_results() and WP_User_Query::get_total().

In both of these public methods, they simply return a parameter. In essence, the following two examples are the same for getting/accessing the results of the query:
[php]<?php
$author_query = new WP_User_Query( $args );
$authors = $author_query->get_results();
[/php]
[php]<?php
$author_query = new WP_User_Query( $args );
$authors = $author_query->results;
[/php]

Likewise, the same is true for get_total() method. The following two examples are the same for getting the total number of users from the WP_User_Query:
[php]<?php
$author_query = new WP_User_Query( $args );
$total = $author_query->get_total();
[/php]
[php]<?php
$author_query = new WP_User_Query( $args );
$total_authors = $author_query->total_users;
[/php]

Written by Travis Smith · Categorized: WordPress

StudioPress Premium WordPress Themes     WP Engine Managed WordPress Hosting

What can I do for you!?

Custom Development

We develop plugins by determining both business/functional and technical requirements, following WordPress development best practices, and using agile methodology to ensure you get the best solution.

Consulting

Have questions? Need a reliable developer to consult? Please contact us today!

Customized Theme

We can customize your theme or child theme, or create a child theme for you based on your needs while enhancing the performance of every individual attribute.

Customized Plugin

We can customize your plugins, extend plugins (e.g., Gravity Forms, Jetpack, Soliloquy) based on your needs ensuring security, performance, and positive business impact.

Contact Us

About Travis Smith

As a WordPress enthusiast, developer, and speaker, Travis writes about what he learns in WordPress trying to help other WordPress travelers, beginners and enthusiasts with tutorials, explanations, & demonstrations.

Comments

  1. PauldeWouters (@PauldeWouters) says

    August 16, 2012 at 7:25 am

    thanks for doing this! I love the query_arg trick to identify the main query 🙂

    Reply
  2. Pippin says

    August 16, 2012 at 10:39 am

    Excellent one, Travis.

    I’d never thought of the query_id trick for identifying your unique query. Props.

    FYI, your comment form tab index is getting confused with your sidebar form.

    Reply
  3. Maltpress says

    October 28, 2012 at 12:08 pm

    Fantastic – just wanted to say thanks for the orderby example, had been struggling with that! No idea why WP_User_Query doesn’t have the orderby => meta_value that WP_Query does…

    Reply
  4. Kathy says

    December 19, 2012 at 3:12 pm

    Thank you! This is awesome. Pippin is correct that tabbing through the form jumps me all over the page.

    Also, wanted to ask quickly about the meta_key called wpsand_capabilities in the examples for everyone “but” certain roles. Should that be wp_capabilities or is that specific to your database somehow?

    Reply
    • Travis Smith says

      December 23, 2012 at 8:38 pm

      It could be wp_capabilities but I always change the wp_ prefix. For the sandbox on my local harddrive it was wpsand_.

      Reply
      • Tiago Celestino says

        March 31, 2013 at 12:13 am

        Can use var global $wpdb and properties $wpdb->prefix

        Reply
        • Travis Smith says

          May 30, 2013 at 11:48 pm

          Yes, that is correct.

          Reply
  5. Shelly says

    March 11, 2013 at 8:46 pm

    Why won’t this work with meta_query? I need to sort my list by last name, but I also have to check yet another met key/value set (for approval in the listing). I can get this to work as ou state above, but when I pop it into a meta_query (so I can look for last name AND for the meta_key = “approved” AND meta_value = “yes”) it doesn’t work anymore.

    How would you make that work?

    Reply
  6. Steve says

    September 8, 2013 at 11:46 am

    Re-ordering my users by last name was exactly what I needed, so this has saved me a lot of frustration. I thought I was going to have to painstakingly recreate my query. Thanks so much.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Twitter
  • Facebook
  • LinkedIn
  • Google+
  • RSS

Copyright © 2025 � WP Smith on Genesis on Genesis Framework � WordPress � Log in