I’ve already read How to switch between the Primary Menus programmatically? but it doesn’t actually answer the question. The accepted answer is just two workarounds but not an actual answer to the question.
When my theme is activated, I create several menus and I would like to mark one of them as the Primary Menu.
Is there a wordpress function I can call to make my programmatically created menu the Primary Menu? I’m an experienced developer, but I’m new to wordpress and the terminology in the functions makes it very hard to search the codex to find what I’m looking for. Any help is appreciated.
I dug through the wordpress code to see what was happening when I submitted the form from the admin UI to see what function it was calling (and did a var_export()
on the variable being passed in) and saw it was calling set_theme_mod( 'nav_menu_locations', $menu_locations );
. I’ve updated my code to use this and it seems to be working:
$locations = get_theme_mod('nav_menu_locations');
$locations['primary'] = $menu_id;
set_theme_mod( 'nav_menu_locations', $locations );
One of the things that threw me off when I was trying to figure out how to do this is that the documentation for get_theme_mod()
says that it returns a string, but in this case it is returning an array and so I didn’t think it was going to work.