通过更新到WP 4.7,忽略了对WordPress API V2的额外参数和查询

时间:2017-01-23 16:11:48

标签: javascript php wordpress wordpress-rest-api

我的网站一直在使用WordPress REST API V2插件。我使用下面的代码添加了一个额外的参数(过滤器),我可以在调用使用自定义分类topics标记的帖子时使用。该网站需要能够在查询中添加多个分类术语,并显示包含任何指定条款的帖子,但只显示指定了其中一个术语的帖子。

add_action( 'rest_query_vars', 'custom_multiple_topics' );
function custom_multiple_topics( $vars ) {
    array_push( $vars, 'tax_query' );
    return $vars;
}

add_action( 'rest_post_query', 'custom_topic_query', 10, 2 );
function custom_topic_query( $args, $request ) {

    if ( isset($args[ 'topics' ]) ) {
        $pre_tax_query = array(
            'relation' => 'OR'
        );

        $topics = explode( ',', $args['topics'] );  // NOTE: Assumes comma separated taxonomies
        for ( $i = 0; $i < count( $topics ); $i++) {
            array_push( $pre_tax_query, array(
                'taxonomy' => 'topic',
                'field' => 'slug',
                'terms' => array( $topics[ $i ] )
            ));
        }

        $tax_query = array(
            'relation' => 'AND',
            $pre_tax_query
        );

        unset( $args[ 'topics' ] );  // We are replacing with our tax_query
        $args[ 'tax_query' ] = $tax_query;
    }

} // end function

示例API调用将是这样的:http://example.com/wp-json/wp/v2/posts?per_page=10&page=1&filter[topics]=audit,data

这一切都很有效,直到更新到WordPress 4.7。更新后,这些参数将被忽略。我不知道从哪里开始解决这个问题。在网站上没有PHP或Javascript错误,自定义过滤器被忽略。更新后,所有帖子都会使用此查询显示,无论它们被标记为什么。

是否有人因更新而遇到此问题?

1 个答案:

答案 0 :(得分:1)

我找到了解决这个问题的方法。事实证明,更新后不再使用操作rest_query_vars

解决方案很简单。我必须更新触发rest_post_query操作的代码,以测试$request而不是$args

以下是我的解决方案,它取代了问题中的所有代码:

add_action( 'rest_post_query', 'custom_topic_query', 10, 2 );
function custom_topic_query( $args, $request ) {

    if ( isset($request['filter']['topics']) ) {
        $pre_tax_query = array(
            'relation' => 'OR'
        );

        $topics = explode( ',', $request['filter']['topics'] );  // NOTE: Assumes comma separated taxonomies
        for ( $i = 0; $i < count( $topics ); $i++) {
            array_push( $pre_tax_query, array(
                'taxonomy' => 'topic',
                'field' => 'slug',
                'terms' => array( $topics[ $i ] )
            ));
        }

        $tax_query = array(
            'relation' => 'AND',
            $pre_tax_query
        );

        $args[ 'tax_query' ] = $tax_query;
    }

} // end function

请注意,我已使用$args[ 'topics' ]

替换了每个$request['filter']['topics']