Posted By

depiction on 04/20/13


Tagged


Versions (?)

WordPress: Print Current Post Categories Hierarchically for Custom Taxonomies


 / Published in: PHP
 

If you create a custom taxonomy there is no real easy way to print out the categories in client format. This code will print out all taxonomies a current post is associated with in a hierarchical unordered list.

  1. <ul>
  2. <?php
  3. $termCount = 0;
  4. $customCategories = get_the_terms( $post->ID, 'bd_categories' );
  5. foreach( $customCategories as $term ) {
  6. if( $term->parent == 0) {
  7. $currentTerm = $term->term_id;
  8. foreach( $customCategories as $term2 ) {
  9. if( $term2->parent == $currentTerm ) {
  10. $termCount++;
  11. }
  12. }
  13. if($termCount == 0) {
  14. echo '<li><a href="'.get_term_link($term->slug, 'bd_categories').'">'.$term->name.'</a></li>';
  15. } else {
  16. echo '<li><a href="'.get_term_link($term->slug, 'bd_categories').'">'.$term->name.'</a>';
  17. echo "<ul>";
  18. foreach( $customCategories as $term2 ) {
  19. if( $term2->parent == $currentTerm ) {
  20. echo '<li><a href="'.get_term_link($term2->slug, 'bd_categories').'">'.$term2->name.'</a></li>';
  21. }
  22. }
  23. echo "</ul></li>";
  24. }
  25. }
  26. }
  27. ?>
  28. </ul>

Report this snippet  

You need to login to post a comment.