wp_setup_nav_menu_item
云策文档标注
概述
wp_setup_nav_menu_item 是一个 WordPress 过滤器,用于修改导航菜单项对象。它允许开发者在菜单项对象被设置时,自定义其属性,如 URL 或类型。
关键要点
- 这是一个过滤器钩子,用于过滤导航菜单项对象。
- 参数 $menu_item 是菜单项对象,可以修改其属性。
- 在 WordPress 3.0.0 版本中引入。
- 常用于应用开发中,调整菜单项 URL 以匹配自定义路由结构。
代码示例
function filter_nav_menu_items($menu){
$post_type = ($menu->object); //gets post type
//if post type is a page, then create a new URL
if ($post_type === 'page') {
$current_url = $menu->url; //grab the current url link
$new_url = '/pages' . str_replace( 'http://example.com/', '/', $current_url ); //replace the base url with a '/'
$menu->url = $new_url; //save the new url to the url property in the menu item object
}
return $menu; //return the filtered object
}
add_filter( 'wp_setup_nav_menu_item', 'filter_nav_menu_items', 1 );注意事项
使用此过滤器时,确保正确处理菜单项对象,避免破坏默认导航功能。示例中展示了如何基于 post_type 修改页面 URL,开发者可根据需求调整逻辑。
原文内容
Filters a navigation menu item object.
Parameters
$menu_itemobject-
The menu item object.
Source
return apply_filters( 'wp_setup_nav_menu_item', $menu_item );
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |
Skip to note 2 content
Nate Finch
In some cases when using WordPress for application development, you might need to change the url structure of a page url in the nav menu to reflect your routing setup to maintain an app-like state.
In this example, we want to filter all nav menu links in the menu item object that are pages, and change them from the default
http://example.com/target-page/to a prefixed slug like/pages/target-page/to meet out routing needs. To do this, filter the menu item object like so:function filter_nav_menu_items($menu){ $post_type = ($menu->object); //gets post type //if post type is a page, then create a new URL if ($post_type === 'page') { $current_url = $menu->url; //grab the current url link $new_url = '/pages' . str_replace( 'http://example.com/', '/', $current_url ); //replace the base url with a '/' $menu->url = $new_url; //save the new url to the <code>url</code> property in the menu item object } return $menu; //return the filtered object } add_filter( 'wp_setup_nav_menu_item', 'filter_nav_menu_items', 1 );