2017-06-23 57 views
0

我必须在单组合页面中显示顶级分类。显示当前单个帖子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; 
?> 

任何人都知道解决方案?

回答

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

+0

我必须添加$ parent_term = get_term_children($条款而─>父, 'portfolio_cat');也在$ term_list之前,如果,现在eveything运作良好!谢谢! – alice

相关问题