如果您可以控制wp_nav_menu()
调用,可以实现自定义Walker_Nav_Menu
class 用于对将导航菜单项数组呈现为HTML进行细粒度控制。
如果要添加的项目的标记与默认值相同Walker_Nav_menu
已生成,您可以使用\'wp_get_nav_menu_items\'
filter 钩住以添加;虚拟导航菜单项;在将对象处理为HTML之前,将其添加到数组中:
/**
* Add a login/logout link to the nav menu in the `primary` location, as a child
* of a menu item for a Page with the slug `members` (if present).
*
* @see https://wordpress.stackexchange.com/a/390893/25324
*
* @param WP_Post[] $items The WP_Post objects representing menu items in this menu.
* @param WP_Term $menu The WP_Term object representing this menu.
* @param array $args The arguments used to retrieve menu items associated with this menu.
* @return array The filtered $items array.
*/
function wpse390890_insert_primary_nav_login_link( $items, $menu, $args ) {
if( is_admin() )
return $items;
// Bail out if this menu isn\'t `primary` or `primary` is being loaded in the dashboard.
if( $menu->slug !== \'primary\' || is_admin() )
return $items;
// Find the ID of the Page with the slug `members` in the menu items.
foreach( $items as $item ) {
if( $item->post_type !== \'page\' || $item->post_name !== \'members\' )
continue;
$members_page_id = $item->ID;
break;
}
// Bail if the `members` page is not in this menu.
if( ! isset( $members_page_id ) )
return $items;
$logged_in = is_user_logged_in();
$link_title = __( $logged_in ? \'Log In\' : \'Log Out\', \'wpse390890\' );
// Insert a new WP_Post object for the link.
$items[] = new WP_Post(
(object) [
\'ID\' => \'user-login\',
\'menu_item_parent\' => $members_page_id,
\'classes\' => [ \'member-auth-link\' ],
\'type\' => \'virtual\',
\'object\' => \'virtual\',
\'title\' => $link_title,
\'attr_title\' => $link_title,
\'url\' => $logged_in ? wp_logout_url() : wp_login_url(),
]
);
return $items;
}
add_filter( \'wp_get_nav_menu_items\', \'wpse390890_insert_primary_nav_login_link\', 10, 3 );
看见
wp_setup_nav_menu_item()
\'s implementation 有关要指定哪些字段以及如何指定的提示
WP_Post
对象将转换为表示导航菜单项的对象。
var_dump()
ing公司
$items
在上面的过滤器中,也是探索菜单中已有项目的格式和属性的好方法。