如果要在每次页面调用时动态添加项目,可以查看以下答案:
Dynamically add sub-categories to any category in the menu
要直接添加元素,您可以尝试将其用于自定义链接,例如:
// create the new element
$post = [
\'post_title\' => "StackExchange " . date("H:i:s"),
"menu_order" => 700, // position in the menu
\'post_type\' => \'nav_menu_item\',
\'post_status\' => \'publish\',
];
$menu_item_db_id = wp_insert_post( $post );
update_post_meta( $menu_item_db_id, \'url\', "https://wordpress.stackexchange.com/");
update_post_meta( $menu_item_db_id, \'type\', "custom");
update_post_meta( $menu_item_db_id, \'_menu_item_menu_item_parent\', 0); // change to create a sub menu
// association to the menu
$menuLocations = get_nav_menu_locations();
$menuID = (int) $menuLocations[\'primary\'];
wp_set_object_terms($menu_item_db_id, $menuID, "nav_menu");