WordPress tutorial: wp_get_nav_menus — how to get all WordPress menus with PHP
Marc Wagner
April 17, 2023
WordPress has a built-in feature called wp_get_nav_menus()
, which allows you to get 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 calls all menus and lists the linked 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 then output for each menu and all linked 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 retrieve the menu items. The code then uses another foreach
loop to iterate through all the menu items and list them.
Conclusion #
Thanks to the built-in wp_get_nav_menus() and wp_get_nav_menu_items() functions in WordPress, it is very easy to retrieve all menus in WordPress using PHP. With the two functions we can quickly and easily create a list of all the menus on the website. This allows you to customize your menus and optimize them for your visitors.
Artikel von:
Marc Wagner
Hi Marc here. I’m the founder of Forge12 Interactive and have been passionate about building websites, online stores, applications and SaaS solutions for businesses for over 20 years. Before founding the company, I already worked in publicly listed companies and acquired all kinds of knowledge. Now I want to pass this knowledge on to my customers.