将Wordpress类别显示为分层

时间:2018-07-23 12:16:59

标签: wordpress wordpress-theming categories

我正在尝试使用以下代码打印与帖子相关的类别。默认情况下,它似乎按字母顺序排序。有没有一种方法可以按类别层次结构对其进行排序?

<footer class="categories-links">
<?php $post_category = get_the_category($post->ID); if ( $post_category==true 
) { ?>  
<span > <?php the_category(' ') ?></span> <?php }?>
</footer>

目前我有例如: 父类别:水果, 子类别:树木, 子子类别:苹果

它打印为苹果-水果-树木。 而必须是水果-树木-苹果

1 个答案:

答案 0 :(得分:0)

您可以尝试一下。这来自Stackexchange。但这是获得的完美方法 您也可以按类别传递$args。有关更多info

  hierarchical_category_tree( 0 ); // the function call; 0 for all categories; or cat ID  

function hierarchical_category_tree( $cat ) {
    // wpse-41548 // alchymyth // a hierarchical list of all categories //

  $next = get_categories('hide_empty=false&orderby=name&order=ASC&parent=' . $cat);

  if( $next ) :    
    foreach( $next as $cat ) :
    echo '<ul><li><strong>' . $cat->name . '</strong>';
    echo ' / <a href="' . get_category_link( $cat->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $cat->name ) . '" ' . '>View ( '. $cat->count . ' posts )</a>  '; 
    echo ' / <a href="'. get_admin_url().'edit-tags.php?action=edit&taxonomy=category&tag_ID='.$cat->term_id.'&post_type=post" title="Edit Category">Edit</a>'; 
    hierarchical_category_tree( $cat->term_id );
    endforeach;    
  endif;

  echo '</li></ul>'; echo "\n";
}  
相关问题