Original question
How do I get menu items using slug and not ID
I need to get a specific menu, but I can’t use ID, since the menu ID
on my dev is not the same as on my staging and prod server.WP doc says that
wp_get_nav_menu_items
can be used with menu slug.
But how do I know what slug is created? I tested with what I thought
would be a slug, but I got no menu items.
My initial though was that I needed to fetch a menu in order to get menu items in an array / object so that I could add an extra menu item.
There is little documentation on how one can get a menu item by using a slug, so I got a bit stuck. If you should have the answer, please add this as well.
My goal was to add a ‘home’ link based on a specific condition.
Thanks to the feedback, I have rewritten my question so it makes more sense 😉
So, based on your comment:
I’m going to propose a solution that will allow you to add a “Home” menu item to any menu, based on arbitrary conditions, using the
wp_nav_menu_items
filter (see tutorial here):If you need to limit the filter further, perhaps to filter only certain
theme_location
outputs, let me know, and I’ll update. Also, if you can describe your actual conditionals, I’ll add those as well.You can get menus using
theme_location
parameter, see codex page for more information.This is how Twenty Eleven gets menu using this method – http://core.trac.wordpress.org/browser/trunk/wp-content/themes/twentyeleven/header.php#L118
You want to display a specific menu? why not use a simpler function,
wp_nav_menu
, and pass an argument of your desirable menu name? just replace your menu name with $menu_name in the next example:more about that function:
http://codex.wordpress.org/Function_Reference/wp_nav_menu
You can use
wp_get_nav_menu_object
to get the nave menu by ID, slug or name (matches in that order).To get the menu object by theme location you can use this function (see related question)
Stored in the menu object
$menu_obj;
is the ID:$menu_obj->ID;
Of course, if you are simply displaying the menu, as the other two answers have said you can use
wp_nav_menu
which accepts ID, slug or name (matches in that order)