Set the active Navigation Menu from a plugin

Is there a way to set the following option from a WordPress plugin, if you know the name of the menu you want to set:
enter image description here

My developer says it’s not possible, but I am sure on of you gurus knows a way around this 😉

Solutions Collecting From Web of "Set the active Navigation Menu from a plugin"

You can use the wp_nav_menu_args filter ( Codex reference ) to set a theme location to use a specific menu.

Example:

function test_wp_nav_menu_args( $args = '' ) {
    // only set menu for the primary navigation menu.
    if ( $args['theme_location'] != 'primary' ) {
        return $args;
    }
    // change {main-menu} to be the slug of the menu you want to set.
    $args['menu'] = 'main-menu';
    return $args;
}
add_filter( 'wp_nav_menu_args', 'test_wp_nav_menu_args' );

You can use get_theme_mod and set_theme_mod to save nav menu locations.

Get locations:

$locations = get_theme_mod( 'nav_menu_locations' );
var_dump( $locations );

prints:

Array
(
    [primary] => 0
    [secondary] => 0
)

Get existing nav menus:

$nav_menus = get_terms( 'nav_menu', array( 'hide_empty' => true ) );
var_dump( $nav_menus );

prints:

Array
(
    [0] => stdClass Object
        (
            [term_id] => 2
            [name] => Main
            [slug] => main
            [term_group] => 0
            [term_taxonomy_id] => 2
            [taxonomy] => nav_menu
            [description] => 
            [parent] => 0
            [count] => 3
        )
}

Set location:

$nav_menu_id = $nav_menus[0]->term_id;
$location = 'primary';
$locations[ $location ] = $nav_menu_id;
set_theme_mod( 'nav_menu_locations', $locations );