Filter REST API Results by Allowed Custom Fields
Lets REST API requests filter posts by custom fields you allow, e.g. /wp-json/wp/v2/posts?meta_key=location&meta_value=paris, for apps and headless front ends.
Opens WPIDE on
Code
// Post type => meta keys that may be used as REST filters.
$wpide_rest_meta_filters = array(
'post' => array( 'location', 'featured' ),
);
foreach ( $wpide_rest_meta_filters as $wpide_rest_type => $wpide_rest_keys ) {
add_filter( "rest_{$wpide_rest_type}_query", function ( $args, $request ) use ( $wpide_rest_keys ) {
$key = $request->get_param( 'meta_key' );
$value = $request->get_param( 'meta_value' );
if ( is_string( $key ) && in_array( $key, $wpide_rest_keys, true ) && is_scalar( $value ) && '' !== (string) $value ) {
$args['meta_query'] = isset( $args['meta_query'] ) ? (array) $args['meta_query'] : array();
$args['meta_query'][] = array( 'key' => $key, 'value' => sanitize_text_field( (string) $value ) );
}
return $args;
}, 10, 2 );
add_filter( "rest_{$wpide_rest_type}_collection_params", function ( $params ) use ( $wpide_rest_keys ) {
$params['meta_key'] = array( 'description' => 'Custom field to filter by.', 'type' => 'string', 'enum' => array_values( $wpide_rest_keys ) );
$params['meta_value'] = array( 'description' => 'Value the custom field must have.', 'type' => 'string' );
return $params;
} );
}
Notes
Only the listed keys can be used, so private fields stay unqueryable. The parameters also appear in the endpoint's schema.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.