你可以试试这个代码。第一个过滤器用于自定义小部件参数,第二个过滤器用于菜单生成。
add_filter("widget_nav_menu_args", function ($nav_menu_args, $nav_menu, $args, $widget_instance) {
$post = get_queried_object();
if (is_a($post, "WP_Post")) {
$nav_menu_args["remove_post_in_widget"] = $post->ID;
}
return $nav_menu_args;
}, 10, 4);
add_filter("wp_nav_menu_objects", function ($sorted_menu_items, $args) {
if (isset($args->remove_post_in_widget)) {
foreach ($sorted_menu_items as $index => $item) {
if ((int) $item->object_id === $args->remove_post_in_widget) {
unset($sorted_menu_items[$index]);
break; // stop the loop when the first post is found
}
}
}
return $sorted_menu_items;
}, 10, 2);