1. Code
  2. Creative Coding

Using WordPress for Web Application Development: WP_User_Query

Read Time:8 minsLanguages:

In this series, we've been taking a look at how WordPress can be used to development web applications much like a number of different frameworks and other tools that are available.

Starting in the last article, we began looking at the different options that we have as it relates to querying the WordPress data. First, we reviewed WP_Query.

In this article, we're going to continue looking at the available options for retrieving information from the database by looking at WP_User_Query after which we'll turn our attention to how we can run direct SQL queries against the database.

But for now, let's take a look at what WordPress offers us in the way of managing our users, their information, and their associated meta data.

Querying The Database: A Refresher

Before we get into discussing the actual API, let's quickly review some of the information about the WordPress database so that we have set a common level of information off of which to work for the remainder of the article, the API, and the examples we'll be covering.

In the last article, we mentioned three specific points:

  1. Querying the WordPress database refers to the act of retrieving information from the database (as is the case with the rest of database-backed web applications).
  2. There are a number of ways to query the database - some of which are more correct than others in some situations - and we need to understand which ways lend themselves to the best situation.
  3. It's important to understand the APIs so that we know what's available to us, what benefit each offers, and which situations are best suited for a given API.

When we covered WP_Query, we reviewed how it can be used to retrieve posts, pages, custom post types, related taxonomies, categories, terms, and so on.

Introducing WP_User_Query

Similarly, WP_User_Query offers much of the same functionality but within the context of users. The Codex defines the query:

WP_User_Query is a class, ..., that allows querying WordPress database tables 'wp_users' and 'wp_usermeta'.

Unlike the intial definition of WP_Query, this is less technical and relatively easy to understand especially if you're familiar with the wp_users table and the wp_usermetadata tables.

But if you're not, no big deal: We're going to be covering everything that's needed not only to understand the tables, but to understand the API, as well.

How To Use WP_User_Query

The wp_users table and the wp_usermetadata tables are responsible for storing user data.

The Table Schema

The information for each of the tables is available in the Codex (which you can find here and here), and I recommend that everyone review it; however, the information about each table can be simplified as follows:

  • The users table maintains the list of users in the system, and the minimum amount of information to give a user access to WordPress. This includes the automatically assigned ID, their login, password, how to display their name, their email address, when they registered, their status, and the URL to their site (if specified).
  • The usermeta table is used to store more generic information through simple key/value pairs. That is to say that, just as with post data, we can associate information with users using their IDs, meta keys, and meta values.

To see this in action, you can take a peek at any WordPress database table information, and you'll find that this is where information such as the First Name, Last Name, Capabilities, and so on.

The nice thing is that if you're building an application, then the meta table provides a lot of flexibility as to how much information you can really associate with any of your users.

Using WP_User_Query

First, note that setting up a user query is much like setting up a WP_Query. By that, I mean that you grab an instance of the class by passing an array of arguments into the constructor.

Now, as far as the arguments are concerned, anything that's contained within the associated database tables can be specified. For example, you can search using:

  • the user role,
  • string matches on columns (such as the ID, the login, the URL, and so on),
  • email address,
  • and so on.

But there's more to it than that. You can also specify parameters relating to meta data so that you can query for various users, say, based on their role and a collection of user meta information.

We'll take a look at this a little bit more in detail momentarily, but it's also worth noting that you can construct even more advanced queries that deal with including pieces of user meta data, excluding user meta data, how and want to order the data (say, by ascending username), and even pagination parameters so that we can page through user records with ease.

A Practical Example

Of course, what good is it to talk about an API without actually looking at how to use it? In the following example, we're going to take an example of user accounts, and then iterate on the query until we have constructed one that attempts to demonstrate a variety of features that it provides.

With that said, let's say that we want to achieve the following:

  • retrieve all administrators,
  • who have a first name specified,
  • ordered by their registration date in ascending order,
  • and paginate so that we only retrieve a number of users per page

So, let's get started. Remember, we're going to be building this query line by line, so it should be relatively easy to understand as it continues to evolve.

If, at any point, you have questions about what's going on, then feel free to drop them in the comments.

First, we want to specify that we want to include all administrators:

After that, we want to make sure they have their first name and last specified. Since that information is stored in the meta data table, we'll need to user parameters for the meta query.

Specifically, we're going to ask to retrieve all of the administrators who have a first name that is specified (or, rather, that is not empty).

Next up, we're going to order the results by the administrators' registration date in ascending order:

And finally, we'll say that we want to pull back five records at a time:

And we're done. Now it's a matter of iterating through the query in order to output our results. Unfortunately, we all may have a different take on how we want to do this, so note that the loop that I'm showing is but one example (versus the example):

And note: One difference from WP_User_Query versus WP_Query is that there's no need to reset any kind of post data because we're not working with anything other than a self-contained loop.

When To Use WP_User_Query

At this point, the quest naturally arises of when is a good idea to use WP_User_Query, and you'll likely get different answers from different people, as some preview to use other methods to retrieve their information.

But, generally speaking, if I'm going to be retrieving information from the database that deals directly and strictly with users, then I use WP_User_Query.

Now, since the result set can be returned in a way that could technically be merged, or at least reworked with another set of data, then it's definitely possible to do this; however, I personally think that this requires a bit of experience that may not fit the bill for everyone.

In other words, feel free to use it as you like, but treat it with caution.

Next Up, Direct Queries Against The Database

So with WP_Query and WP_User_Query behind us, we've got one more API at which we can look in order to round out our discussion, and that's the ability to directly query the WordPress database.

In the final article dealing with queries, we'll take a look at this API, finish up our discussion, and then head into the final review of everything we've covered throughout this series.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.