我正在尝试从当前帖子中获取父类别和子类别。
自定义帖子类型称为 assortiment
,自定义分类称为 assortiment-categorie
。
我们有一个名为 SL524CB – 500kg
的产品,其父类别 Test
和子类别(Test
)test b
。
现在我做了一个循环,输出子类别名称(test b
),但我们还需要父类别名称(Test
)。
为了输出它们,我们需要 2 个变量,例如 $parent_category
和 $subcategory
,以便我们可以在我们的模板中输出它们。
这是我们现在使用的循环:
<?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;
?>
如果有人能帮助我那就太好了,谢谢您的时间!
答案 0 :(得分:1)
我们可以通过多种方式实现这一目标。
@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()
返回特定术语的子项。
将所有 term 子项合并到一个 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 ', ';
};
答案 1 :(得分:0)
$categories = get_the_terms( get_the_ID(), 'category' );
echo "<pre>"; print_r($categories); echo "</pre>";
如果您打印 $categories
,那么您将得到如下输出。您可以在其中确定 $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;
}
}