0

I have created a menu and I have the ID.

$menu_id = wp_create_nav_menu( 'Main Menu' );

And I have registered a navigation menu location:

register_nav_menus(
    array(
        'menu-header' => 'Header menu',
    )
);

How to set "Display location" for this menu?

3
  • what are you trying to do that requires this? I can write an answer to this question, but if you asked about the problem you're trying to solve then there are better ways to do that and you will get better more usable answers. E.g. are you trying to create and pre-fill menus when you activate a theme or plugin? Dynamically create menus and locations on the fly?
    – Tom J Nowell
    Commented Nov 21, 2022 at 18:07
  • Note that there are several things you could be doing that people regularly do that require what you're asking that have major problems and super easy alternatives
    – Tom J Nowell
    Commented Nov 21, 2022 at 18:11
  • @TomJNowell I'm just trying to create a predefined menu for a new MU site.
    – djanym
    Commented Nov 21, 2022 at 18:15

1 Answer 1

1

You can retrieve nav menu locations with get_nav_menu_locations

int[] Associative array of registered navigation menu IDs keyed by their location name. If none are registered, an empty array.

https://developer.wordpress.org/reference/functions/get_nav_menu_locations/

This refers to a theme mod internally named nav_menu_locations which can be used to update the locations.

You can modify that returned value and then save the new array like this:

// Update theme mod
$locations = get_nav_menu_locations();
$locations['menu-header'] = $menu_id;
set_theme_mod( 'nav_menu_locations', $locations );

Note that this won't run filters and actions, caches may not be updated as a result, etc.

I'd also note that if you're trying to create side menus for dynamically generated content that this does not scale, and you will run into issues. There are better ways to show content specific menus and sidebars that do not involve the creation of nav menus.

0

Your Answer

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

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