Posted By

innerstorm on 10/07/11


Tagged

wordpress categories subcategory subcategories


Versions (?)

list top parent category of post and parent's subcategories


 / Published in: PHP
 

  1. /**
  2.  * list of post's top parent category as a h3 and all subcategories of it,
  3.  * current post's category highlighted with a class
  4.  */
  5.  
  6. function list_subcategories () {
  7. $hide_empty = 0;
  8. $current_class = 'current_item';
  9. global $post;
  10.  
  11. //id of the current post
  12. $this_post_ID = $post->ID;
  13.  
  14. //categories list of curent post
  15. $categories = get_the_category($post->ID);
  16.  
  17. //first category, parent category of current post
  18. $category_id = $categories[0]->cat_ID;
  19.  
  20. // if it's not root category (0) then do
  21. if ($category_id) {
  22.  
  23. // get alphabetical list of parent categories separated with ","
  24. $parentCatList = get_category_parents( $category_id, false, ",");
  25.  
  26. // get first category slug of that list...
  27. $topParentSlug = substr( $parentCatList, 0, strpos($parentCatList, ',') );
  28.  
  29. // get the object of that slug
  30. $topParent = get_term_by( 'slug', $topParentSlug, 'category' );
  31.  
  32. // get the id of that object
  33. $ancestor = $topParent->term_id;
  34.  
  35. // echo the name of the parent category
  36. echo "<h3>$topParent->name</h3>";
  37.  
  38. //list of parent category's categories
  39. echo '<ul>';
  40.  
  41. // making the array of subcategories objects
  42. $cat_array = get_categories( "echo=0&title_li=&depth=$levels&child_of=$ancestor&hide_empty=$hide_empty" );
  43.  
  44. foreach($cat_array as $category) {
  45.  
  46. // if the listed cat. is the current post's category, we set it as current
  47. if ( $category_id == $category->cat_ID ) { $is_current = "class='" .$current_class."'"; }
  48.  
  49. // list the category with a link
  50. echo '<li '. $is_current .'><a href="'.get_category_link( $category->term_id ).'">'. $category->name.'</a></li>';
  51.  
  52. }
  53. echo "</ul>";
  54. }
  55. }

Report this snippet  

You need to login to post a comment.