admin管理员组

文章数量:1316827

When my custom theme gets activated, it programatically creates some default pages with custom templates, a nav menu, and several menu items. This saves me a lot of time not having to do those same steps over and over on every site. However, if I want to customize the menu on a site by adding additional menu items specific to that site, the menu is not there when I go to to Appearance -> Menus. Is there a way to make it appear, along with the menu items that were created programatically, and be editable?

Here's the code I use to create the menu and menu items:

function wts_create_and_register_menus() {

  $primary_menu = 'Primary Navigation';
  $footer_menu = 'Footer Navigation';

  register_nav_menus(
    array(
      'primary-menu'   => $primary_menu,
      'footer-menu' => $footer_menu
    )
  );

  if( wp_get_nav_menu_object( $primary_menu ) ) {
    $menu_id = wp_create_nav_menu( $primary_menu );

    // Primary menu items to create
    $menu_titles = array( 'Services', 'Gallery', 'FAQs', 'Blog', 'Contact' );
    $menu_urls= array( '/services/', '/gallery/', '/faqs/', '/blog/', '/contact/' );

    for($i = 0; $i < count($menu_titles); $i++) {
      wp_update_nav_menu_item($menu_id, 0, array(
        'menu-item-title' =>  __( $menu_titles[$i] ),
        'menu-item-url' => home_url( $menu_urls[$i] ),
        'menu-item-status' => 'publish')
      );
    }

    $locations = get_theme_mod('nav_menu_locations');
    $locations['primary-menu'] = $menu_id;
    set_theme_mod('nav_menu_locations', $locations);
  }

}

add_action("after_switch_theme", "wts_create_and_register_menus"); 
add_theme_support( 'menus' );

Just an FYI, I had to add the very last line of this code ( add_theme_support( ' menus' ); ) after adding the code above it to my functions.php. When I was doing everything manually, it wasn't necessary to have that line. But now that I'm creating the menu programatically, I'll get the error: "Your theme does not support navigation menus or widgets" without that line.

Thanks in advance for your help.

本文标签: theme developmentProgramatically Created Menu not Editable in Dashboard