WP API V2:通过ACF查询帖子

问题描述 投票:0回答:1

我想通过过滤添加了高级自定义字段的自定义元来查询我的帖子。这是一个布尔元,所以每个帖子都会有类似的内容:

获取http://localhost/wp-json/wp/v2/posts

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

即使我在

function.php
中将meta_key和meta_value暴露给REST API,我也无法按此元值进行过滤:

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');

但是如果我尝试:

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

我看到所有帖子就好像过滤器被忽略一样。

php wordpress rest advanced-custom-fields wp-api
1个回答
5
投票

我能够通过此定制解决这个问题:

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 );

并以这种方式进行查询(突出显示是acf boolean)

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

© www.soinside.com 2019 - 2024. All rights reserved.