我尝试使用以下代码在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”。怎么了?这是个好钩子吗?如何在主查询完成之前正确添加分类筛选?
提前感谢您的回答!
最合适的回答,由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;
}