POST API Tax_Relationship字段不起作用

时间:2022-01-06 作者:MattRogowski

我试图用如下URL查询包含所有提供的标记的帖子:

/wp-json/wp/v2/posts?tags=22,23&tax_relation=AND

然而,它仍然返回带有任何标签的帖子,而不是所有标签。

我查了WP的代码,从wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php:

private function prepare_tax_query( array $args, WP_REST_Request $request ) {
    $relation = $request[\'tax_relation\'];

    if ( $relation ) {
        $args[\'tax_query\'] = array( \'relation\' => $relation );
    }

    $taxonomies = wp_list_filter(
        get_object_taxonomies( $this->post_type, \'objects\' ),
        array( \'show_in_rest\' => true )
    );

    foreach ( $taxonomies as $taxonomy ) {
        $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;

        $tax_include = $request[ $base ];
        $tax_exclude = $request[ $base . \'_exclude\' ];

        if ( $tax_include ) {
            $terms            = array();
            $include_children = false;
            $operator         = \'IN\';

            if ( rest_is_array( $tax_include ) ) {
                $terms = $tax_include;
            } elseif ( rest_is_object( $tax_include ) ) {
                $terms            = empty( $tax_include[\'terms\'] ) ? array() : $tax_include[\'terms\'];
                $include_children = ! empty( $tax_include[\'include_children\'] );

                if ( isset( $tax_include[\'operator\'] ) && \'AND\' === $tax_include[\'operator\'] ) {
                    $operator = \'AND\';
                }
            }
应应用AND 子句为该位:

if ( isset( $tax_include[\'operator\'] ) && \'AND\' === $tax_include[\'operator\'] ) {
    $operator = \'AND\';
}
但有几条线是这样的:

$tax_include = $request[ $base ];
如果我把$tax_include, 我明白了:

Array
(
    [0] => 22
    [1] => 23
)
所以我不明白WP的一半代码应该如何工作?这个termsinclude_childrenoperator 上永远不存在密钥$tax_include 因为它只是请求中的一个ID数组。

如果在初始代码块之后手动添加此项:

$operator = \'AND\';
它工作正常,可以匹配所有标签。

当然这是WP中的一个bug,完全不起作用,还是我误解了什么?

1 个回复
最合适的回答,由SO网友:MattRogowski 整理而成

因此,事实证明,这在5.7中已完全更改,文档也没有更新以反映这一点,这是毫无帮助的。更多信息请访问Git commit.

而不是:

/wp-json/wp/v2/posts?tags=22,23&tax_relation=AND

此URL有效:

/wp-json/wp/v2/posts?tags[terms]=22,23&tags[operator]=AND