Divide categories into main and sub list
-
Hi,
I am quite new to WorPress and I was puzzled when trying to split my categories into a main menu (main categories), shown at the top of my page, and a sub menu (sub categories) shown at the right.
A. TOP: CAT A, CAT B, CAT C, CAT D, CAT E
Getting the main categories out of wordPress wasn’t that hard. I simply used, <?php wp_list_cats(‘children=0&hide_empty=0’); ?>
B. Right: CAT B1
CAT B2
CAT B21
CAT B3However, retrieving the category sublist turned out to be a little more daunting though amd I stumbled across a number of solutions in this forum which use <?php wp_list_cats(‘child_of=’.$cat);?>. Now what this does is that it takes the ID of the active category, e.g. CAT B, and retrieves all of its sub categories, such as CAT B1, B2 etc.
However, the problem is that as soon as you navigate deeper into the sub categories all of the cats lying above will disappear. For example if you selected CAT B2, wp_list_cats would only display CAT B21, i.e. the child of CAT B2.
Since this didn’t come up to my requirements I created a function which always finds the top level/main category ID instead. Thus, whatever category you select in the sub category tree it will still display the entire sub list.
-
<?php function category_get_top_parent_id ($child = 0) {
global $wpdb;if(is_numeric($child) && $child > 0){
$category_parent = $wpdb->get_var(“SELECT category_parent FROM $wpdb->categories WHERE cat_ID =$child”);
if($category_parent == 0){$result = $child;}
else{
$result = category_get_top_parent_id($category_parent);}
}
else{
$result = 0;
}
return $result;
}$topParentID = category_get_top_parent_id($cat); ?>
<?php wp_list_cats(‘child_of=’.$topParentID.’&hide_empty=0′);?>
- The topic ‘Divide categories into main and sub list’ is closed to new replies.