Development & EngineeringApr 17, 2023
WordPress Guide: wp_get_nav_menus - How to Query All WordPress Menus with PHP
WordPress has a built-in function called wp_get_nav_menus() that allows you to query all WordPress menus with PHP. The function returns an array of all registered menus. We can use this function in our PHP code to retrieve all menus and then process them further.
Code Example
To retrieve all menus in WordPress with PHP, we can use the following code:
$menus = wp_get_nav_menus();
foreach ( $menus as $menu /** @var WP_Term $menu */ ) {
echo '<h2>' . $menu->name . '</h2>';
$menu_items = wp_get_nav_menu_items( $menu->term_id );
if ( ! empty( $menu_items ) ) {
echo '<ul>';
foreach ( $menu_items as $menu_item ) {
echo '<li><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
}
echo '</ul>';
}
}This code retrieves all menus and lists the associated menu items. The code uses a foreach loop to iterate through each menu in the wp_get_nav_menus() array. Within this loop, a heading (<h2>) is output for each menu, and all associated menu items are listed.
The wp_get_nav_menu_items() function is used to retrieve the menu items for each menu. This function requires the term_id attribute of the menu as a parameter to fetch the menu items. The code then uses another foreach loop to iterate through all menu items and list them.
Conclusion
Thanks to the built-in functions wp_get_nav_menus() and wp_get_nav_menu_items() in WordPress, it is very easy to retrieve all menus in WordPress with PHP. With these two functions, we can quickly and easily create a list of all menus on the website. This allows you to customize your menus and optimize them for your visitors.