通过API函数,我想定义一个新的Navigation菜单,在当前主题中选择它,然后插入几个Pages作为菜单项。例如,这将在主题激活时完成。
在手动设置“导航”菜单和项目之后,通过一个(相当痛苦的)反向工程过程,数据库插入和更新,我完成了以下步骤,其中“ footer-nav”是“导航”菜单的子ID。 m创建:
if (!term_exists('footer-nav', 'nav_menu')) {
$menu = wp_insert_term('Footer nav', 'nav_menu', array('slug' => 'footer-nav'));
// Select this menu in the current theme
update_option('theme_mods_'.get_current_theme(), array("nav_menu_locations" => array("primary" => $menu['term_id'])));
// Insert new page
$page = wp_insert_post(array('post_title' => 'Blog',
'post_content' => '',
'post_status' => 'publish',
'post_type' => 'page'));
// Insert new nav_menu_item
$nav_item = wp_insert_post(array('post_title' => 'News',
'post_content' => '',
'post_status' => 'publish',
'post_type' => 'nav_menu_item'));
add_post_meta($nav_item, '_menu_item_type', 'post_type');
add_post_meta($nav_item, '_menu_item_menu_item_parent', '0');
add_post_meta($nav_item, '_menu_item_object_id', $page);
add_post_meta($nav_item, '_menu_item_object', 'page');
add_post_meta($nav_item, '_menu_item_target', '');
add_post_meta($nav_item, '_menu_item_classes', 'a:1:{i:0;s:0:"";}');
add_post_meta($nav_item, '_menu_item_xfn', '');
add_post_meta($nav_item, '_menu_item_url', '');
wp_set_object_terms($nav_item, 'footer-nav', 'nav_menu');
}
这似乎可行,但是:
- 这是一种强大而优雅的方法吗?
- 我是否缺少可以在一行代码中完成所有这些工作的完全显而易见的东西?