Make Theme automatically choose default nav menu

I have been developing a WordPress theme. I want to be able to, once activated, look to see if there is already a menu created in the backend. If it exists then choose it and use as the primary menu, but otherwise create a new menu with the top level pages already in existence and register it as the primary menu.

I can’t seem to find much on this, can anyone shed any light?

We have found some code that checks the current default menu listed below

add_action( 'after_switch_theme',  'mytheme_menu_fix' );

function mytheme_menu_fix() {


    $old_theme = get_option( 'theme_switched' );
    $old_theme_mods = get_option("theme_mods_{$old_theme}");
    $old_theme_navs = $old_theme_mods['nav_menu_locations'];
    $new_theme_navs = get_theme_mod( 'nav_menu_locations' );

    if (!$new_theme_navs) {
     $new_theme_locations = get_registered_nav_menus();

    foreach ($new_theme_locations as $location => $description ) {
         $new_theme_navs[$location] = $old_theme_navs[$location];
    }

    set_theme_mod( 'nav_menu_locations', $new_theme_navs );

    }
}

This works fine, all we need to sort now is if no primary nav is selected. I.E. on a fresh install of the theme

Solutions Collecting From Web of "Make Theme automatically choose default nav menu"

You can use has_nav_menu() to check to see if the location has one assigned to it. If it does, use wp_get_nav_menu_items() to duplicate the menu, then assign it to the location you register in your theme.

Here’s what I have in mind. It’s off the top of my head and will need more code and testing, but hopefully it’s a good start for you:

function wpse112672_menus() {
    if( has_nav_menu( 'old_theme_menu_location' ) {
        $old_menu = wp_get_nav_menu_items( 'old_menu_id' );
        register_nav_menu( 'new_theme_menu_location' );
        $new_menu = wp_nav_menu( $args );

        return $new_menu;
    } else {
        return wp_page_menu();
    }
}