在当前单个 post 类型上显示当前顶级分类法 - Wordpress
Display current top level taxonomy on current single post tye - Wordpress
我必须在单一投资组合页面中显示顶级分类。
此代码仅在有子类别时对我有效,
一些投资组合项目没有子类别,在这种情况下,它不显示父分类(显然没有父分类)
<?php
// variable for location
$term_list = '';
$terms = get_the_terms( $post->ID, 'portfolio_cat' );
$prefix = '';
foreach( $terms as $term ) {
$parent_term = get_term( $term->parent, 'portfolio_cat' );
$term_list .= $prefix . $parent_term->name;
$prefix = ', ';
}
// output
echo $term_list;
?>
有人知道解决方案吗?
您应该使用 subcategory
检查当前类别的子元素,如果可用,则您可以打印当前父类别。
<?php
// variable for location
$term_list = '';
$terms = get_the_terms( $post->ID, 'portfolio_cat' );
$prefix = '';
foreach( $terms as $term ) {
$parent_term = get_term_children( $term->parent, 'portfolio_cat' );
if(count($parent_term) > 0){
$term_list .= $prefix . $parent_term->name;
$prefix = ', ';
}else{
$term_list .= $prefix . $term->name;
$prefix = ', ';
}
}
// output
echo $term_list;
?>
https://developer.wordpress.org/reference/functions/get_the_terms/
https://codex.wordpress.org/Function_Reference/get_term_children
我必须在单一投资组合页面中显示顶级分类。
此代码仅在有子类别时对我有效, 一些投资组合项目没有子类别,在这种情况下,它不显示父分类(显然没有父分类)
<?php
// variable for location
$term_list = '';
$terms = get_the_terms( $post->ID, 'portfolio_cat' );
$prefix = '';
foreach( $terms as $term ) {
$parent_term = get_term( $term->parent, 'portfolio_cat' );
$term_list .= $prefix . $parent_term->name;
$prefix = ', ';
}
// output
echo $term_list;
?>
有人知道解决方案吗?
您应该使用 subcategory
检查当前类别的子元素,如果可用,则您可以打印当前父类别。
<?php
// variable for location
$term_list = '';
$terms = get_the_terms( $post->ID, 'portfolio_cat' );
$prefix = '';
foreach( $terms as $term ) {
$parent_term = get_term_children( $term->parent, 'portfolio_cat' );
if(count($parent_term) > 0){
$term_list .= $prefix . $parent_term->name;
$prefix = ', ';
}else{
$term_list .= $prefix . $term->name;
$prefix = ', ';
}
}
// output
echo $term_list;
?>
https://developer.wordpress.org/reference/functions/get_the_terms/
https://codex.wordpress.org/Function_Reference/get_term_children