保存新帖子后,可以使用此代码。否则,此时没有post对象。
请注意代码未经测试。
<?php
// get post ID from the URL query
$post_id = $_GET[\'post\'];
// get post object
$new_item_to_add = get_post($post_id, OBJECT);
// get menu to add the item into (change to the relevant slug, ID, or name)
$existing_menu = wp_get_nav_menu_object(\'test-nav-menu-slug\');
$existing_menu_id = $existing_menu->term_id;
$new_menu_item_data = array(
\'menu-item-db-id\' => $menu_item_db_id, // default 0, creates a new one
\'menu-item-object-id\' => $post_id,
\'menu-item-object\' => \'\', //default
\'menu-item-parent-id\' => 0, //default
\'menu-item-position\' => 0, //default
\'menu-item-type\' => $new_item_to_add->post_type,
\'menu-item-title\' => $new_item_to_add->post_title,
\'menu-item-url\' => get_permalink($post_id),
\'menu-item-description\' => \'\', //default
\'menu-item-attr-title\' => \'\', //default
\'menu-item-target\' => \'\', //default
\'menu-item-classes\' => \'\', //default
\'menu-item-xfn\' => \'\', //default
\'menu-item-status\' => \'publish\',
);
wp_update_nav_menu_item($existing_menu_id, $menu_item_db_id = 0, $new_menu_item_data);
请参见
wp_update_nav_menu_item 代码参考。
还有一种更糟糕的方法。您可以动态更改菜单。这不会更新菜单:
<?php
function wpse267737_add_nav_menu_items($nav_menu_items) {
// get post ID from URL
$post_id = $_GET[\'post\'];
// get current post data
$link_url = get_permalink( $post_id );
$link_anchor = get_the_title( $post_id );
// build new menu item
$new_menu_item = \'<li><a href="\' . $link_url . \'">\' . $link_anchor . \'</a></li>\';
// concatenate existing items and new
$nav_menu_items .= $new_menu_item;
return $nav_menu_items;
}
// change TEST-MENU-SLUG to the relevant menu slug
add_filter( \'wp_nav_menu_TEST-MENU-SLUG_items\', \'wpse267737_add_nav_menu_items\' );
请参见
wp_nav_menu_items 参考