问题描述
我想在WP_Query循环中输出一个列表,其中包含各个帖子的特定分类法(“体裁”)的术语ID。我设法输出了第一个ID(如代码示例所示)。如何在'terms'
数组中获得'tax_query'
的分类法“体裁”的所有术语ID的逗号分隔列表?
function my_function( $query_args) {
$terms = get_the_terms( $post->ID,'genre');
$termlist = $terms[0]->term_id;
$query_args = array(
'post_type' => 'portfolio','orderby' => 'date','order' => 'ASC','tax_query' => array(
array(
'taxonomy' => 'genre','field' => 'term_id','terms' => array($termlist),),);
return $query_args;
}
解决方法
要按您的条款返回所有ID,您需要使用以下代码:
$term_ids = []; // Save into this array all ID's
// Loop and collect all ID's
if($terms = get_terms('genre',[
'hide_empty' => false,])){
foreach($terms as $term) {
$term_ids[]=$term->term_id; // Save ID
}
}
现在,您可以按特定术语使用术语ID数组,并且可以使用join(',',$term_ids)
函数以逗号分隔的ID列表或所需列表。
但是,如果您想通过特定帖子收集所有术语ID,则需要这样的内容:
$terms_ids = [];
if($terms = get_the_terms( $POST_ID_GOES_HERE,'genre')){
foreach($terms as $term) {
$terms_ids[]=$term->term_id;
}
}
但是在使用get_the_terms
之前,必须确保已提供帖子ID或定义的对象ID。
在您的职能中,您缺少该部分。
这是您的功能的更新:
function my_function( $query_args ) {
global $post; // return current post object or NULL
if($post)
{
$terms_ids = array();
if($terms = get_the_terms( $post->ID,'genre')){
foreach($terms as $term) {
$terms_ids[]=$term->term_id;
}
}
$query_args = array(
'post_type' => 'portfolio','orderby' => 'date','order' => 'ASC','tax_query' => array(
array(
'taxonomy' => 'genre','field' => 'term_id','terms' => $terms_ids,),);
return $query_args;
}
}