WordPress Create Menu Locations and Assigning Menus Programmatically

Either in your setup file or in your general functions.php, update and include the following code:

// This theme uses wp_nav_menu() in one location.
register_nav_menu( 'primary', __( 'Primary Menu', 'theme-slug' ) );
//get 'your_custom_menu' id to assign it to the primary menu location created
$menu_header = get_term_by('name', 'your_custom_menu', 'nav_menu');
$menu_header_id = $menu_header->term_id;
//if menu not found, create a new one
if($menu_header_id == 0) {
     $menu_header_id = wp_create_nav_menu('your_custom_menu');
}
//Get all locations (including the one we just created above)
$locations = get_theme_mod('nav_menu_locations');

//set the menu to the new location and save into database
$locations['primary'] = $menu_header_id;
set_theme_mod( 'nav_menu_locations', $locations );

3 thoughts on “WordPress Create Menu Locations and Assigning Menus Programmatically

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s