两个答案都让我走上了正确的道路,但似乎 args 的值取决于 Wordpress 版本(我运行 5.5)或主题(我正在使用 https://underscores.me/ )或其他任何东西(不是超级 WP 专家在这里,刚刚开始深入研究此类 WP 主题)。
如果上述方法对您不起作用,有什么帮助是转储 args 并相应地修改代码。
args 对我的价值:
stdClass::__set_state(array( 'menu' => WP_Term::__set_state(array( 'term_id' => 7, 'name' => 'Menu 1', 'slug' => 'menu-1', 'term_group' => 0, 'term_taxonomy_id' => 7, 'taxonomy' => 'nav_menu', 'description' => '', 'parent' => 0, 'count' => 5, 'filter' => 'raw', )), 'container' => 'div', 'container_class' => '', 'container_id' => '', 'container_aria_label' => '', 'menu_class' => 'menu', 'menu_id' => 'primary-menu', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '
%3$s
', 'item_spacing' => 'preserve', 'depth' => 0, 'walker' => '', 'theme_location' => 'menu-1', ))
所以我去检查taxonomy(也清理了一点代码):
function add_last_nav_item($items, $args) {
// just to show you how to dump it out - remove that line afterwards ofcs
var_export($args);
// If this is the menu you are looking for, add search form
if (isset($args->menu->taxonomy) && $args->menu->taxonomy === 'nav_menu') {
$items .= '<li>' . get_search_form(false) . '</li>';
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'add_last_nav_item', 10, 2);