WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
It sounds like you're trying to duplicate the menu that the previous theme used so there's no loss of menus when your theme is activated, is that right? – morganestes Sep 5 '13 at 20:45
yes, but I also want to create a menu of top level pages if no menu is selected as the primary menu too – manc Sep 6 '13 at 0:37

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();
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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