How to filter users with WP_User_Query and the meta_query argument in WordPress
Nov 03, 2014 by Micro Themes in TutorialsExpand Text
We recently wrapped up a custom WordPress project for a private client and one of the components we had to build for the site was a members directory. The main goal of the directory was to retrieve a dataset of users, display them in chronological order and filter the users based on a custom parameter – so basically only certain users out of the entire wp_user table needed to be fetched from the database.
We decided against using a custom SQL query for filtering the data and instead relied on the WP_User_Query method to handle the task. After a little digging around the WordPress codex and reading up on several tutorials online we put together a custom query to fetch and filter the data we needed from the database. I should also mention that our users have custom meta values tied to their accounts and fortunately for us the WP_User_Query can filter users based on custom meta values.
Here is the code we compiled (the arguments array we passed into WP_User_Query) to fetch our data followed by an explanation of the code:
$args = array( 'role' => 'elite_member', 'meta_key' => 'user_organization', 'orderby' => 'meta_value', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'elite_visible', 'value' => 'on', 'compare' => '=' ), array( 'key' => 'user_organization', 'compare' => 'NOT NULL' ) ) ); $user_query = new WP_User_Query( $args );
As you can see in the code we are fetching users with the role type of elite_member and running two meta queries (within an array) to filter our users based on two key values (elite_visible and user_organization). The first meta query checks to see if the elite_visible value equals on and the second meta query determines if the user_organization value is NOT NULL (meaning it has a value stored in the field). If both of these values are met than the data is successfully fetched from the database (WordPress uses a MySQL database in case you were not aware).
The other values in the code such as number, offset, orderby and meta_key are used for paging and ordering purposes. The main part of the code that we have focused on here is the meta_query array which handles the data filtering.
So there you have it, you now have a reference point for filtering users based on custom user meta data with the WP_User_Query in WordPress.