wp_get_nav_menu_items vs wp_nav_menu

I’m a novice WordPress developer and I’m looking for best way to build custom WordPress menu.

I have found two server side ways to do that, but i don’t understand deeper difference of them

The menu might build with the wp_nav_menu function and for that need crate extends class of Walker_Nav_Menu. For that need have a copy of the main class in your theme and change more code as well

Or we can use wp_get_nav_menu_items function, by giving it the menu location to get the array of all items to build html output. It will be more simple and easy and no need to understand complicated Walker class

So, what the best way to build the menu or what the main difference of these functions.

Thanks

1 Answer
1

wp_get_nav_menu_items function retrieves an array of menu items for given menu. But the menu is a hierarchy, so there is a need of creating some mechanism that will create that hierarchy based on list of menu items.

On the other hand there already is wp_nav_menu, that will get items for that menu (using wp_get_nav_menu_items) and then it will pass it to Walker class that will generate HTML code for this menu. This function will also take care of cases when given menu doesn’t exist and so on. It is the recommended way to display menu in themes.

PS. I don’t get why you think that you “have to” write your own Walker class. You certainly don’t. WP will use it’s own Walker class as default. And if you want to customize the HTML code for that menu, you can write filters and it will be enough most of the times…

Leave a Comment