If you’re working with the All Users screen in WordPress and want to sort all users by metadata, it’s possible with the pre_get_users
hook.
In WordPress, though, there’s a handful of pieces of data that you’ll need to work with this hook. Namely:
- the meta key off of which you want to read the information,
- how you want to order the query,
- and how to set up the meta query.
Additionally, if you just want to run the query on the All Users page, it’s helpful to prevent the query from running except for where you want it.
Sort All Users by Metadata
First, here’s a simple helper function that we can use to determine if we’re on the users.php
page within the WordPress administration area.
/** * Determines if we're on the users.php page. * * @return bool True if we're on the users page. */ function isOnUsersPage() { return str_contains($_SERVER['REQUEST_URI'], 'users.php'); }
Next, let’s assume that our users have a status of being active or being inactive. That is, we’re maintaining their accounts but perhaps they are no longer active in the system for whatever reason the application calls.
Further, let’s assume these are numeric values where 0
is inactive and 1
is active. Now we can set up the initial function so it looks something like this:
add_action( 'pre_get_users', function ($query) { if (!isOnUsersPage()) { return $query; } // TODO return $query; } );
Note the pre_get_users
hook accepts a function with a single argument – the query running on the page – and this is the query that we will manipulate to order the users by active information.
The passed WP_User_Query object contains the query variables, not yet passed into SQL.
Developer Handbook
We’ll set up an array of arrays (though it’s a single dimensional array) that indicates we’re going to use the status
meta key for querying users.
After that, we’ll do the following:
- set the meta key on the query,
- assign the query in the array of arrays to the
meta_query
attribute.
The code should look like this:
add_action( 'pre_get_users', function ($query) { if (!isOnUsersPage()) { return $query; } $metaQuery = [ [ 'key' => 'status' ] ]; $query->set('meta_key', 'status'); $query->set('meta_query', $metaQuery); // TODO return $query; } );
And since we’re going to be ordering the users in ascending order by their status, we need to also specify the orderby
and the order
for the query:
add_action( 'pre_get_users', function ($query) { if (!isOnUsersPage()) { return $query; } $metaQuery = [ [ 'key' => 'status' ] ]; $query->set('meta_key', 'status'); $query->set('meta_query', $metaQuery); $query->set('orderby', 'meta_value'); $query->set('order', 'asc'); return $query; } );
Note that how the status is set will depend on the plugin you’re working on and whether or not you want to render a column on the All Users page for this. And I can show that in another tip in a future post.