Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.