# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: rest-api, custom-fields, headless
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/dev-rest-filter-by-meta/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Filter REST API Results by Allowed Custom Fields" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
