Jul 17, 2013

Working custom menu in Wordpress with submenu

Recently I had to create a custom menu in Wordpress. Searching how to do it, I stumbled with the wp_get_nav_menu_items function. However, the example shown there does not work in my Wordpress installation. A nice koala-ish guy called ricoh solved this problem in the Wordpress.org forums. But I needed more than that. I needed to place a sub-menu for the children pages of a certain page, and that wasn't made in the solution ricoh provided. So I took his solution and extended it to make this possible.

Please also note that I added an extra DIV to contain it all and make it easily customizable via CSS. Also note that I added some standard Wordpress classes to the items of the lists, so it matches closely the output of the menu provided by Wordpress. 
 <?  $menu_name = 'your_menu';   
    ?><div class="menu-container menu-custom-<?echo $menu_name?>-container"><?
   
    if ( ($menu = wp_get_nav_menu_object( $menu_name ) ) && ( isset($menu) ) ) {

        $menu_items = wp_get_nav_menu_items($menu->term_id);
        $menu_list = '<ul id="menu-' . $menu_name . '" class="menu">';
        $children = false;
        $pos = 0;
        foreach ( (array) $menu_items as $key => $menu_item ) {           
            $children = $menu_items[$pos+1]->post_parent!=0;
            $parent = $menu_item->post_parent;
            if($parent=='0'){
                $title = $menu_item->title;
                $url = $menu_item->url;               
                $menu_list .= '<li class="menu-item"><a href="' . $url . '">' . $title . '</a>';//</li>';
            }else{
                $menu_list .= '<ul class="sub-menu">';               
                    foreach ( (array) $menu_items as $key2 => $menu_item2 ) {               
                        $parent2 = $menu_item2->post_parent;
                        if($parent==$parent2){
                            $title = $menu_item2->title;
                            $url = $menu_item2->url;
                            $menu_list .= '<li class="menu-item"><a href="' . $url . '">' . $title . '</a></li>';                       
                        }
                    }
                $menu_list .= '</ul>';       
                $menu_list .= '</li>';        //del nivell superior       
            }
           
            if (!$children) $menu_list .= '</li>';
            $pos ++;
        }
        $menu_list .= '</ul>';
    } else {
        $menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
    }
    echo $menu_list;
    ?></div>

Extra tip 1: I placed this code in my sidebar.php file, after commenting the dynamic_sidebar(...) function, disabling the menu I placed there on the backend.

Extra tip 2: if you want your sub-menu items to hide or show on parent's hover, add this CSS:
li.menu-item ul li {display:none;}
li.menu-item:hover ul li {display:block;}
 Have fun and hope this helps you with your custom Wordpress menus!