我需要在将新项目插入WordPress nav menu后运行一些代码。
菜单修改是否有任何钩子或类似的东西?
答案 0 :(得分:0)
您的问题令人困惑,但无论您要求解决方案是save_post action hook
,因为您提到在创建新项目时需要在菜单栏中自动添加菜单项item可以是post/page
甚至是nav_menu_item
,此钩子可以在创建/更新任何这些项目时执行。因此,在functions.php
文件中声明一个钩子,如下所示:
add_action( 'save_post', 'item_has_been_saved' );
function item_has_been_saved($post_id)
{
// $post_id is the newly created or updated item
// use this $post_id to get the item and check it's type
$item = get_post($post_id);
//'post','page','link','nav_menu_item' or any custom post
if($item->post_type == 'page') {
$menu = wp_get_nav_menu_object('menu_name_goes_here');
$menu_items = wp_get_nav_menu_items($menu->term_id);
foreach ( (array) $menu_items as $key => $menu_item ) {
if($menu_item->post_name != $item->post_name) continue;
else return false; // already exists
}
$newItem = array(
'menu-item-title' => $menu_item->title,
'menu-item-classes' => $menu_item->title,
'menu-item-url' => $menu_item->url,
'menu-item-status' => 'publish'
);
wp_update_nav_menu_item($menu->term_id, 0, $newItem);
}
}