如果要使用wp_get_nav_menu_items
钩住,然后尝试下面的函数,该函数应在exclude_menu_items
功能:
// Example when NOT using a class: (you already defined the exclude_menu_items function)
add_filter( \'wp_get_nav_menu_items\', \'exclude_menu_items\', 10, 3 );
add_filter( \'wp_get_nav_menu_items\', \'exclude_menu_items2\' );
function exclude_menu_items2( $items ) {
if ( current_user_can( \'administrator\' ) ) {
return $items;
}
$mores = [];
$parents = [];
foreach ( $items as $key => $item ) {
if ( \'#\' === $item->url && \'More\' === $item->title ) {
$mores[] = $item->ID;
}
if ( ! in_array( $item->menu_item_parent, $parents ) ) {
$parents[] = $item->menu_item_parent;
}
}
$mores = array_diff( $mores, $parents );
foreach ( $items as $i => $item ) {
if ( in_array( $item->ID, $mores ) ) {
unset( $items[ $i ] );
}
}
return $items;
}
只需确保运行适当的验证,以便菜单项不会被弄乱,例如在菜单管理屏幕上。
这两种功能也可以组合使用:
function exclude_menu_items( $items, $menu, $args ) {
if ( current_user_can( \'administrator\' ) ) {
return $items;
}
$mores = [];
$parents = [];
foreach ( $items as $key => $item ) {
if ( $page = get_post( $item->object_id ) ) {
// ... your code here.
}
if ( ! empty( $items[ $key ] ) ) {
if ( \'#\' === $item->url && \'More\' === $item->title ) {
$mores[] = $item->ID;
}
if ( ! in_array( $item->menu_item_parent, $parents ) ) {
$parents[] = $item->menu_item_parent;
}
}
}
$mores = array_diff( $mores, $parents );
foreach ( $items as $i => $item ) {
if ( in_array( $item->ID, $mores ) ) {
unset( $items[ $i ] );
}
}
return $items;
}
事实上;什么时候
wp_nav_menu()
称为—使用
wp_nav_menu_objects
hook, 删除没有子项的“更多”项目更简单:
add_filter( \'wp_nav_menu_objects\', function ( $items ) {
if ( is_admin() ) { // sample validation..
return $items;
}
return array_filter( $items, function ( $item ) {
return ! ( \'#\' === $item->url && \'More\' === $item->title &&
! in_array( \'menu-item-has-children\', $item->classes )
);
} );
} );