Site icon WP Smith

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]