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:
- Create a new menu in the WordPress dashboard by going to Appearance > Menus.
- Add items to the menu and organize them into sub-menus by using the drag-and-drop interface.
- Use the
wp_nav_menufunction to display the menu in your theme. This function takes an array of arguments, including themenuargument, which should be set to the name or ID of the menu you want to display. - Use the
wp_get_nav_menu_itemsfunction to retrieve the items in the menu. This function takes the ID, slug, or name of the menu as its argument. - Loop through the items returned by
wp_get_nav_menu_itemsand use themenu_item_parentproperty to determine if an item is a parent or child item. - Check if a menu item has children by looking for other items where
menu_item_parentmatches the item's ID. - Use the
titleandurlproperties to output the link and label for each menu item. - Use
ifandelsestatements to check if the current menu item is a parent or child and display it accordingly. - If an item is a parent, recursively process its children from the same array instead of calling
wp_get_nav_menu_items()again. - 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.