在主题激活时,以下代码不会使用“新建页面”项创建我的菜单,创建菜单并将位置分配给“子菜单”,但没有我新建页面的菜单项?
我错过了什么?
<?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);
}
}
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\' ) );
}
这可能无法解决您的问题。如果不了解更多关于主题设置的知识,我就无法测试一些东西。