W3docs

How do I generate a custom menu/sub-menu system using wp_get_nav_menu_items in WordPress?

To generate a custom menu/sub-menu system using wp_get_nav_menu_items in WordPress, you can follow these steps:

To generate a custom menu/sub-menu system using wp_get_nav_menu_items in WordPress, you can follow these steps:

  1. Create a new menu in the WordPress dashboard by going to Appearance > Menus.
  2. Add items to the menu and organize them into sub-menus by using the drag-and-drop interface.
  3. Use the wp_nav_menu function to display the menu in your theme. This function takes an array of arguments, including the menu argument, which should be set to the name or ID of the menu you want to display.
  4. Use the wp_get_nav_menu_items function to retrieve the items in the menu. This function takes the ID, slug, or name of the menu as its argument.
  5. Loop through the items returned by wp_get_nav_menu_items and use the menu_item_parent property to determine if an item is a parent or child item.
  6. Check if a menu item has children by looking for other items where menu_item_parent matches the item's ID.
  7. Use the title and url properties to output the link and label for each menu item.
  8. Use if and else statements to check if the current menu item is a parent or child and display it accordingly.
  9. If an item is a parent, recursively process its children from the same array instead of calling wp_get_nav_menu_items() again.
  10. Repeat steps 7 and 8 for child items as well.

Here is a complete code example demonstrating the recursive loop and HTML output structure:

function display_custom_menu( $items, $parent_id = 0 ) {
    $children = array_filter( $items, function( $item ) use ( $parent_id ) {
        return $item->menu_item_parent == $parent_id;
    } );

    if ( ! empty( $children ) ) {
        echo '<ul>';
        foreach ( $children as $child ) {
            echo '<li>';
            echo '<a href="' . esc_url( $child->url ) . '">' . esc_html( $child->title ) . '</a>';
            // Recursively display sub-menu
            display_custom_menu( $items, $child->ID );
            echo '</li>';
        }
        echo '</ul>';
    }
}

// Usage in your theme template:
$menu_items = wp_get_nav_menu_items( 'Primary Menu' );
if ( $menu_items ) {
    display_custom_menu( $menu_items, 0 );
}

It's also a good idea to customize the output of your menu using CSS to match the design of your website.