主题激活时未创建菜单项

时间:2013-08-09 作者:erichmond

在主题激活时,以下代码不会使用“新建页面”项创建我的菜单,创建菜单并将位置分配给“子菜单”,但没有我新建页面的菜单项?

我错过了什么?

<?php
if (isset($_GET[\'activated\']) && is_admin()){
    $new_page_title = \'New Page\';
    $new_page_slug = \'/new-page/\';
    $new_page_content = \'This is the page content\';
    $new_page_template = \'page-job-list.php\'; //ex. template-custom.php. Leave blank if you don\'t want a custom page template.
    //don\'t change the code bellow, unless you know what you\'re doing
    $page_check = get_page_by_title($new_page_title);
    $new_page = array(
            \'post_type\' => \'page\',
            \'post_title\' => $new_page_title,
            \'post_content\' => $new_page_content,
        \'post_status\' => \'publish\',
        \'post_author\' => 1,
);
if(!isset($page_check->ID)){
        $new_page_id = wp_insert_post($new_page);
        if(!empty($new_page_template)){
                update_post_meta($new_page_id, \'_wp_page_template\', $new_page_template);
        }
}

// Check if the menu exists
$menu_name = \'AnotherMenu\';
$menu_exists = wp_get_nav_menu_object( $menu_name );

// If it doesn\'t exist, let\'s create it.
if( !$menu_exists){
    $menu_id = wp_create_nav_menu($menu_name);

    wp_update_nav_menu_item($menu_id, $new_page_id, array(
        \'menu-item-title\' =>  __($new_page_title),
        \'menu-item-url\' => home_url( $new_page_slug ), 
        \'menu-item-status\' => \'publish\'));
}

$menulocation = \'submenu\';

if(!has_nav_menu($menulocation) ){
    $locations = get_theme_mod(\'nav_menu_locations\');
    $locations[$menulocation] = $menu_id;  //$foo is term_id of menu
    set_theme_mod(\'nav_menu_locations\', $locations);
}
}

1 个回复
SO网友:Charles Clarkson

的价值$menu_id 如果菜单已存在,则未初始化。所以,如果主题激活,$menu_exists 是真的,$menu_id 将永远不会设置为值,此行应生成PHP警告:

$locations[$menulocation] = $menu_id;
您可以尝试这样添加:

if ( $menu_exists ) {
    $menu_id = $menu_exists->term_id;

} else {
    // Menu doesn\'t exist, let\'s create it.
    $menu_id = wp_create_nav_menu( $menu_name );

    wp_update_nav_menu_item( $menu_id, $new_page_id, array(
        \'menu-item-title\' =>  __( $new_page_title ),
        \'menu-item-url\' => home_url( $new_page_slug ),
        \'menu-item-status\' => \'publish\' ) );
}
这可能无法解决您的问题。如果不了解更多关于主题设置的知识,我就无法测试一些东西。

结束

相关推荐

How to add taxonomy in menus?

书籍(自定义帖子类型)小说(税)科学(税)历史(税)--书籍体裁(税务)小说(术语)科学(学期)历史(学期)以下哪一项是做这件事的“好方法”?对于前一个(这是我目前在管理菜单中的功能,我为每个功能都提供了“register\\u taxonomy”功能),我无法选择要在菜单中显示的“Tax”。而对于后者,我可以将它们添加到菜单中,只需要一个“register\\u taxonomy”函数。