phpwordpressrestadvanced-custom-fieldswp-api

WP API V2: Query posts by ACF


I would like to query my posts by filtering for a custom meta added with Advanced Custom Fields. It's a boolean meta, so every post will have something like:

GET http://localhost/wp-json/wp/v2/posts

{
  ...
  "acf" : {
    "highlight" : true
  }
  ...
}

I'm not able to filter by this meta value, even if I exposed meta_key and meta_value to the REST API in function.php:

function my_add_meta_vars ($current_vars) {
    $current_vars = array_merge ($current_vars, array ('meta_key', 'meta_value'));
    return $current_vars;
}
add_filter ('rest_query_vars', 'my_add_meta_vars');

But if I try:

GET http://localhost/wp-json/wp/v2/posts?filter[meta_key]=highlight&filter[meta_value]=true

I see all the posts as if the filter is ignored.


Solution

  • I was able to get this solved with this customization:

    add_filter( 'rest_query_vars', function ( $valid_vars ) {
        return array_merge( $valid_vars, array( 'highlight', 'meta_query' ) );
    } );
    add_filter( 'rest_post_query', function( $args, $request ) {
        $highlight   = $request->get_param( 'highlight' );
    
        if ( ! empty( $highlight ) ) {
            $args['meta_query'] = array(
                array(
                    'key'     => 'highlight',
                    'value'   => $highlight,
                    'compare' => '=',
                )
            );      
        }
    
        return $args;
    }, 10, 2 );
    

    And do a query in this way (highlight is acf boolean)

    GET /wp-json/wp/v2/posts?highlight=1