2

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.

2 Answers 2

5

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.

3

Sounds like you are looking for this:

Add to functions.php

$locations = get_theme_mod('nav_menu_locations');
$locations['primary-menu'] = $term_id_of_menu;
set_theme_mod( 'nav_menu_locations', $locations );

Source: https://stackoverflow.com/a/19637827/7243209

1
  • 1
    I figured out something similar just now, but primary-menu did not work for me, I had to use the key primary instead. That's what the core WP code is using when it does the update. Jun 1, 2018 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.