Reputation: 365
Hello I have a script that displays all categories in wordpress menu but I want to add subcategories to this menu too. How I can check if categories have subcategories then display them in submenu of category.
$items .= '<ul class="sub-menu">';
$categories = get_categories();
foreach ($categories as $category) {
$option = '<li><a href="'.get_category_link( $category->term_id ).'">';
$option .= $category->cat_name;
$option .= '</a></li>';
$items .= $option;
}
$items .= '</ul></li>';
Upvotes: 0
Views: 1095
Reputation: 101
get_categories() only fetches categories and subcategories those are assigned to any post(s) unless you pass array("hide_empty"=>0) as parameter to fetch inactive categories/subcategories too
try below
$items .= '<ul class="sub-menu">';
$categories = get_categories(array("hide_empty"=>0,'parent'=> '0'));
foreach ($categories as $category) {
$childrens = get_categories(array('child_of'=>$category->term_id,"hide_empty"=>0));
$subitems ='';
if(count($childrens)>0){
$subitems .= '<ul class="sub-menu">';
foreach($childrens as $children){
$opt = '<li><a href="'.get_category_link($children->term_id ).'">';
$opt .= $children->cat_name;
$opt .= '</a></li>';
$subitems .= $opt;
}
$subitems.= '</ul></li>';
}
$option = '<li><a href="'.get_category_link( $category->term_id ).'">';
$option .= $category->cat_name;
$option .= '</a>'.$subitems.'</li>';
$items .= $option;
}
$items .= '</ul></li>';
I know its a dirty way. Don't use "hide_empty"=>0 unless you really need it
Upvotes: 2