[英]Wordpress: Output list with taxonomy term IDs in WP_Query loop
我想在 WP_Query 循環中輸出一個列表,其中包含相應帖子的某個分類法(“流派”)的術語 ID。 我設法輸出了第一個 ID(如您在代碼示例中所見)。 如何獲取'tax_query'
數組中'terms'
的分類法“genre”的所有術語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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.