Skip to content

Instantly share code, notes, and snippets.

@adamsilverstein
Last active March 23, 2023 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamsilverstein/edb3507806391f652d8c9bcdab28bf53 to your computer and use it in GitHub Desktop.
Save adamsilverstein/edb3507806391f652d8c9bcdab28bf53 to your computer and use it in GitHub Desktop.
class Custom_REST_Users_Controller extends WP_REST_Users_Controller {
/**
* Registers the routes for the controller.
*/
public function register_routes() {
parent::register_routes();
add_filter( 'rest_user_query', array( $this, 'filter_user_query_by_meta_fields' ), 10, 2 );
}
/**
* Filter user query by meta fields.
*
* @param array $args The query arguments.
* @param WP_REST_Request $request The current request object.
* @return array The filtered query arguments.
*/
public function filter_user_query_by_meta_fields( $args, $request ) {
$meta_query = array();
// Get the meta fields to search for.
$meta_fields = $request->get_param( 'meta_fields' );
if ( ! empty( $meta_fields ) ) {
foreach ( $meta_fields as $meta_field ) {
$meta_query[] = array(
'key' => $meta_field['key'],
'value' => $meta_field['value'],
'compare' => $meta_field['compare'],
);
}
}
if ( ! empty( $meta_query ) ) {
$args['meta_query'] = $meta_query;
}
return $args;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment