Allow Filtering by Custom Field | WP ACF API

The code below is assuming there is:

  • A Custom Post Type (CPT)
  • `{type}` is replaced with the slug of the CPT (E.G. `attorney`)
  • Advanced Custom Fields is installed with various fields
  • The plugin called 'ACF to REST API' is installed

This allows filtering via any custom field that belongs to the CPT in the filter name.

Things to note:

  • If multiple filters are passed in the url, then they all must be true for a certain record to return (Think 'WHERE AND').
  • The value must match exactly.


add_filter( 'rest_{type}_query', function( $args ) {

	 $filters = [
	 	 'relation' => 'AND',
	 ];

	 foreach($_GET as $key => $value){
	 	 $filter = [
	 	 	 'key' => $key,
	 	 	 'value' => $value,
	 	 	 'compare' => '='
	 	 ];
	 	 array_push($filters, $filter);
	 }

	 $args['meta_query'] = $filters;

	 return $args;
} );