问题描述

Theres 一种在 pre_get_posts 过滤器中使用 $query->set('tax_query', ...)的方法?例如下一个代码不会更改查询。请注意,我正在建立自定义搜索的分类法。

function custom_search_filter($query) {
        ...

        // array('taxonomy' => 'category', 'field' => 'id', 'terms' => array( 41,42 ), 'operator' => 'IN')
        $taxonomies = implode(',', $taxonomy_arr);

        // https://wordpress.stackexchange.com/questions/25076/how-to-filter-wordpress-search-excluding-post-in-some-custom-taxonomies

        $taxonomy_query = array('relation' => 'AND', $taxonomies);

        $query->set('tax_query', $taxonomy_query);
    }

    return $query;
}


add_filter( 'pre_get_posts', 'custom_search_filter', 999 );

提前致谢。

最佳解决方案

过滤器中的 $query 变量表示 WP_Query 对象,因此您不应将新的 WP_Query 对象传递到用于设置该对象属性的方法中。

question you copied code from 错误地使用过滤器,我觉得这是您问题的关键。

是的,tax_query 可以在 pre_get_posts(或类似的 parse_request) 过滤器/动作中使用。

以下是一个示例:为搜索查询指定自定义分类法

function search_filter_get_posts($query) {
    if ( !$query->is_search )
        return $query;

    $taxquery = array(
        array(
            'taxonomy' => 'career_event_type',
            'field' => 'id',
            'terms' => array( 52 ),
            'operator'=> 'NOT IN'
        )
    );

    $query->set( 'tax_query', $taxquery );

}
add_action( 'pre_get_posts', 'search_filter_get_posts' );

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。