显示当前单个帖子上的当前顶级分类 - Wordpress

时间:2017-06-23 08:37:19

标签: custom-wordpress-pages

我必须在单一投资组合页面中显示顶级分类。

只有存在子类别时,此代码才适用于我, 一些投资组合项目没有子类别,在这种情况下,它没有显示父分类法(显然没有父分类法)

<?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;
?>

任何人都知道解决方案吗?

1 个答案:

答案 0 :(得分:0)

您应该使用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