如何在查询过程中添加分类过滤器?

时间:2015-04-20 作者:Nicolas BONNIOT

我尝试使用以下代码在pre\\u get\\u posts挂钩上添加税务查询:

    // Add custom posts to main query (archive and home)
add_action( \'pre_get_posts\', \'add_post_types_to_query\' );

function add_post_types_to_query( $query ) {
    if ( (is_home() || is_category() || is_search()) && $query->is_main_query() && !is_admin() )
    {
        // Query all posts on index and category pages
        $query->set( \'post_type\', array( \'post\', \'page\', \'definition\', \'video\', \'data_vizualization\', \'quizz\', \'talk\', \'question\', \'study\', \'bibliography\' ) );

        $workspace_taxonomy_query =
                    array(array(
                        \'taxonomy \' =>  \'workspace\',
                        \'field\'     =>  \'slug\',
                        \'terms\'     =>  array(\'particulier\'),
                        \'operator\'  =>  \'IN\'
                    ));
        $query->tax_query->queries[] = $workspace_taxonomy_query;
        $query->set( \'tax_query\', $workspace_taxonomy_query);
    }
    return $query;
}
该代码给出了以下where子句:“0=1”。怎么了?这是个好钩子吗?如何在主查询完成之前正确添加分类筛选?

提前感谢您的回答!

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

您有语法错误或拼写错误。在您的tax_query 大堆如果这是总数,我会发表评论,但除此之外$query->tax_query->queries[] = $workspace_taxonomy_query; 这条线毫无意义。不管有没有它,一切都不会改变。不要试图那样攻击阵列。仅使用$query->set( \'tax_query\', $workspace_taxonomy_query); 如下所示(使用我的测试环境中存在的分类法和术语):

// Add custom posts to main query (archive and home)
add_action( \'pre_get_posts\', \'add_post_types_to_query\' );

function add_post_types_to_query( $query ) {
    if ( (is_home() || is_category() || is_search()) && $query->is_main_query() && !is_admin() )
    {
        // Query all posts on index and category pages
        $query->set( \'post_type\', array( \'post\', \'page\', \'definition\', \'video\', \'data_vizualization\', \'quizz\', \'talk\', \'question\', \'study\', \'bibliography\' ) );

        $workspace_taxonomy_query =
                    array(
                      array(
                        \'taxonomy\' =>  \'post_tag\',
                        \'field\'     =>  \'slug\',
                        \'terms\'     =>  array(\'test-4\'),
                        \'operator\'  =>  \'IN\'
                      )
                    );
        $query->tax_query->queries[] = $workspace_taxonomy_query;

    }
    return $query;
}

结束

相关推荐

Search with filters and title

我想搜索custom_post 按标题和ACF字段。所以,我用了WP_Query WordPress函数,但我不能按标题过滤,只能按过滤器过滤。当我提交表单时,我有这样的URL:http://example.com/?s=titre&filter1=condition1&filter2=condition2&filter3=condition3 我的代码:$title = $_GET[\'s\']; $args = array( \'pagenam