下面是我用来尝试查询一个术语的单一分类法的代码,但排除了该术语返回的、也属于另一个术语的帖子。
在英语中,这就是我想要的:查询“资源类型”中的“证词”,但不要查询同样是“音频”的“证词”。
调整此代码以使其正常工作的提示?
<?php
$testimonials_args = array(
\'post_type\' => \'resource\',
\'posts_per_page\' => 1,
\'tax_query\' => array(
\'relation\' => \'AND\',
array(
\'taxonomy\' => \'resource-type\',
\'field\' => \'slug\',
\'terms\' => array( \'testimonies\' )
),
array(
\'taxonomy\' => \'resource-type\',
\'field\' => \'slug\',
\'terms\' => array( \'audio\' ),
\'operator\' => \'NOT IN\'
)
)
);
?>
最合适的回答,由SO网友:Bainternet 整理而成
我想这是因为您在一个分类法上尝试了两个条件,所以您可以始终创建自定义sql查询,如下所示:
$querystr = "
SELECT *
FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->posts.post_type = \'resource\'
AND $wpdb->posts.post_status = \'publish\'
AND $wpdb->term_taxonomy.taxonomy = \'resource-type\'
AND $wpdb->terms.slug = \'testimonies\'
AND $wpdb->terms.slug NOT IN (\'audio\')
ORDER BY $wpdb->posts.post_date DESC
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
或者,您可以只按一个术语进行查询,并按排除
has_term()
在循环内部,类似这样的内容:
if (!has_term(\'audio\',\'resource-type\',$post->ID)){
//post without audio
}else{
//post with audio (skip or whatever)
}