WordPress tutorial: wp_get_nav_menus — how to get all WordPress menus with PHP

Marc Wag­ner

April 17, 2023

2 min read|

Word­Press has a built-in fea­ture cal­led wp_get_nav_menus(), which allows you to get all Word­Press menus with PHP. The func­tion returns an array of all regis­tered menus. We can use this func­tion in our PHP code to retrie­ve all menus and then pro­cess them fur­ther.

Code example #

To retrie­ve all menus in Word­Press with PHP, we can use the fol­lo­wing 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 lin­ked menu items. The code uses a foreach loop to ite­ra­te through each menu in the wp_get_nav_menus() array. Within this loop, a hea­ding (<h2>) is then out­put for each menu and all lin­ked menu items are lis­ted.

The wp_get_nav_menu_items() func­tion is used to retrie­ve the menu items for each menu. This func­tion requi­res the term_id attri­bu­te of the menu as a para­me­ter to retrie­ve the menu items. The code then uses ano­ther foreach loop to ite­ra­te through all the menu items and list them.

Conclusion #

Thanks to the built-in wp_get_nav_menus() and wp_get_nav_menu_items() func­tions in Word­Press, it is very easy to retrie­ve all menus in Word­Press using PHP. With the two func­tions we can quick­ly and easi­ly crea­te a list of all the menus on the web­site. This allows you to cus­to­mi­ze your menus and opti­mi­ze them for your visi­tors.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar