Is there a good way to separate categories from subcategories in wp

Here are my costume functions that I wrote for the menu and submenu in my wordpress theme, but after I tested it the submenu disappeared when I clicked on a submenu, because wordpress doesnt separate categories from subcategories, so the parameter for them is “cat”, which means that when I click on a submenu then the function that creates the submenu checks if cat=id in the url has child categories but it doesnt becasue it is a child category, I am new into wordpress and I dont know how to deal with it:

function costume_menu() {
$categories =  get_categories('hide_empty=0&style=none&parent=0'); 
  foreach ($categories as $category) {
    (is_category($category->term_id)) ? $active = 'class="active_menu"' : $active = '';
    $nav = '<li>';
    $nav .= '<a '.$active.'href="'.get_category_link($category->term_id).'">'.strtoupper($category->cat_name).'</a>';
    $nav .= '</li>';

    echo $nav;
  }

}

function costume_submenu($cat) {

$categories =  get_categories("child_of=$cat&hide_empty=0"); 
  foreach ($categories as $category) {
    (is_category($category->term_id)) ? $active = 'class="active_menu"' : $active = '';
    $nav = '<li>';
    $nav .= '<a '.$active.'href="'.get_category_link($category->term_id).'">'.strtoupper($category->cat_name).'</a>';
    $nav .= '</li>';

    echo $nav;
  }
}

Related posts

Leave a Reply

1 comment

  1. Try the function like this:

    function costume_submenu($cat) {
        $current_cat=get_category($cat);
        if($current_cat->parent==0)
            $parent_cat=$cat;
        else
            $parent_cat=$current_cat->parent;
    
        $categories =  get_categories("child_of=$parent_cat&hide_empty=0");    
        foreach ($categories as $category) {
            (is_category($category->term_id)) ? $active = 'class="active_menu"' : $active = '';
            $nav = '<li>';
            $nav .= '<a '.$active.'href="'.get_category_link($category->term_id).'">'.strtoupper($category->cat_name).'</a>';
            $nav .= '</li>';
    
            echo $nav;   
        } 
    }