使用主题激活将菜单分配给主题位置

时间:2012-07-11 作者:Ünsal Korkmaz

一个站点正在使用名为“child1”的子主题。当这个站点切换到其他名为“child2”的子主题时,它们的小部件也在移动,但主题位置没有移动。如何在主题激活时自动将菜单分配给主题位置?

我从中找到此解决方案http://wordpress.org/support/topic/how-to-assign-a-wordpress-3-menu-to-primary-location-programmatically

$theme = get_current_theme();
$mods = get_option("mods_$theme");
$key = key($mods[\'nav_menu_locations\']);
$mods[\'nav_menu_locations\'][$key] = $menu_id;
update_option("mods_$theme", $mods);
有没有更好的wordpress方法来解决这个问题?(相关trac主题:http://core.trac.wordpress.org/ticket/18720 )

2 个回复
最合适的回答,由SO网友:Ünsal Korkmaz 整理而成

我写了一个解决方案,所以写在这里:

/* 
 This action copies old theme\'s theme location saves to 
 new theme if new theme doesnt have saves before.
 */
 add_action( \'after_switch_theme\',  \'ajx_theme_locations_rescue\' );
 function ajx_theme_locations_rescue() {
    // bug report / support: http://www.unsalkorkmaz.com/
    // We got old theme\'s slug name
    $old_theme = get_option( \'theme_switched\' );
    // Getting old theme\'s settings
    $old_theme_mods = get_option("theme_mods_{$old_theme}");
    // Getting old theme\'s theme location settings
    $old_theme_navs = $old_theme_mods[\'nav_menu_locations\'];
    // Getting new theme\'s theme location settings
    $new_theme_navs = get_theme_mod( \'nav_menu_locations\' );

    // If new theme\'s theme location is empty (its not empty if theme was activated and set some theme locations before)
    if (!$new_theme_navs) {
        // Getting registered theme locations on new theme
        $new_theme_locations = get_registered_nav_menus();

        foreach ($new_theme_locations as $location => $description ) {
            // We setting same nav menus for each theme location 
            $new_theme_navs[$location] = $old_theme_navs[$location];
        }

        set_theme_mod( \'nav_menu_locations\', $new_theme_navs );

    }
 }

SO网友:Rochelle Cassar

我知道你很久以前就有过这个问题,但由于这个网站出现了前几个问题,我想分享我的解决方案,以防有人需要它。

在安装文件或常规文件中functions.php, 更新并包含以下代码:

// 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 );

结束