How to add custom query filters in WP_User_Query

The pre_user_query action hook in WordPress will allow you alter the SQL statements in the WP_User_Query object before they are run against the database. Note, this is an action, not a filter, so there’s no need to return the $user_query that gets passed in.

add_action( 'pre_user_query', 'add_my_custom_queries' );

function add_my_custom_queries( $user_query ) {

   $user_query->query_fields .= ', my_custom_field ';  // additional fields 
   $user_query->query_from .= ' INNER JOIN my_table '; // additional joins here
   $user_query->query_where .= ' AND field='value' '; // additional where clauses
   $user_query->query_orderby .= ' ORDER BY my_custom_field '; // additional sorting
   $user_query->query_limit .= ''; // if you need to adjust paging

}

Leave a Comment