Get items of a menu and a submenu in WordPress

Is there any way I can get the items of a menu element in wordpress and then, iterating with PHP, for each of its elements get again its submenu elements if there’s any?

I would like to create a custom list and it seeems to me this is easier than dealing with the Walker function.

Related posts

1 comment

  1. I see that the question is old, but this might be a solution to your problem (and others in the future) 🙂

    if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
       $menu_name = 'your-menu-name';
    
       $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
    
       $menu_items = wp_get_nav_menu_items($menu->term_id);
    
       $menu_list = '<ul id="menu-' . $menu_name . '">';
    
       foreach ( (array) $menu_items as $key => $menu_item ) {
           $title = $menu_item->title;
           $url = $menu_item->url;
    
           if( $menu_item->menu_item_parent == 0){ // Parent
               $menu_list .= '<li class="parent"><a href="' . $url . '">' . $title . '</a></li>';
           }else{ // Child
               $menu_list .= '<li class="child"><a href="' . $url . '">' . $title . '</a></li>';
    
           }
       } // END foreach
       $menu_list .= '</ul>';
       echo $menu_list;
    
    } // END if isset
    

    This will loop trough the whole menu, and while in the loop, you can create if-statements if there is a parent or a child.

    Here is all the avalible data in the menu_items object.
    To access them, just do like this in the loop: $menu_item->menu_order. That will give you 1

    [ID] => 143 
    [post_author] => 1 
    [post_date] => 2016-11-22 18:44:19 
    [post_date_gmt] => 2016-11-22 18:44:19 
    [post_content] => 
    [post_title] => Parent 1 
    [post_excerpt] => 
    [post_status] => publish 
    [comment_status] => closed 
    [ping_status] => closed 
    [post_password] => 
    [post_name] => parent-1 
    [to_ping] => 
    [pinged] => 
    [post_modified] => 2016-11-22 18:46:19 
    [post_modified_gmt] => 2016-11-22 18:46:19 
    [post_content_filtered] => 
    [post_parent] => 0 
    [menu_order] => 1 
    [post_type] => nav_menu_item 
    [post_mime_type] => 
    [comment_count] => 0 
    [filter] => raw 
    [db_id] => 143 
    [menu_item_parent] => 0 
    [object_id] => 143 
    [object] => custom 
    [type] => custom 
    [type_label] => Custom Link 
    [title] => Parent 1 
    [url] => # 
    [target] => 
    [attr_title] => 
    [description] => 
    

    The code is from the WordPress docs, you can read more there: wp_get_nav_menu_items

Comments are closed.