[英]Get child and parent category name (custom taxonomy) from current post (custom post type)
我正在嘗試從當前帖子中獲取父類別和子類別。
自定義帖子類型稱為assortiment
,自定義分類稱為assortiment-categorie
。
我們有一個名為SL524CB – 500kg
的產品,其父類別Test
和子類別( Test
) test b
。
現在我做了一個輸出子類別名稱( test b
)的循環,但我們還想要父類別名稱( Test
)。
對於 output 它們,我們需要 2 個變量,例如$parent_category
和$subcategory
,因此我們可以在模板中對它們進行 output。
這是我們現在使用的循環:
<?php
global $post;
$terms = wp_get_object_terms( $post->ID, 'assortiment-categorie', array('fields'=>'names'));
$term_id = array_pop( $terms ); //gets the last ID in the array
echo $term_id;
?>
如果有人可以幫助我,那就太好了,已經感謝您的時間了!
我們可以通過多種方式實現這一目標。
@Chris Haas 評論是一種方法。 我,我更喜歡使用另一種方式。
關於父母,我們可以使用get_term_parents_list()
來返回特定術語的父母。
使用分隔符檢索術語父項。
<?php
$args = array(
'format' => 'slug',
'link' => false,
'inclusive' => false,
);
$parents = explode( '/', get_term_parents_list( $term_id, $taxonomy, $args ) );
$î = 0;
foreach( $parents as $parent ) {
$i++;
echo $parent;
if ( $i !== sizeof( $parents ) )
echo ', ';
};
關於孩子,我們可以使用get_term_children()
它將返回特定術語的孩子。
將所有術語子項合並到其 ID 的單個數組中。
<?php
$children = get_term_children( $term_id, $taxonomy );
$î = 0;
foreach( $children as $child ) {
$i++;
$term = get_term_by( 'id', $child, $taxonomy );
echo $term->name;
if ( $i !== sizeof( $children ) )
echo ', ';
};
使用get_the_terms() 。
$categories = get_the_terms( get_the_ID(), 'category' );
echo "<pre>"; print_r($categories); echo "</pre>";
如果您打印$categories
那么您將有一個 output 如下所示。 您可以在其中確定$term
是parent
或child
。
Array
(
[0] => WP_Term Object
(
[term_id] => 18
[name] => Test 2
[slug] => test-2
[term_group] => 0
[term_taxonomy_id] => 18
[taxonomy] => category
[description] =>
[parent] => 17
[count] => 1
[filter] => raw
)
[1] => WP_Term Object
(
[term_id] => 17
[name] => Test
[slug] => test
[term_group] => 0
[term_taxonomy_id] => 17
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
)
)
試試下面的代碼。
foreach ( $categories as $key => $category ) {
if( $category->parent == 0 ){
echo "Parent => ".$category->name;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.