我有以下功能以选择格式输出一个自定义菜单,用于我正在处理的响应性设计。
它的工作方式正是我想要它除了我需要排除子菜单项。目前,它包括所有级别。
有人知道我怎么说吗wp_get_nav_menu_items
是否只显示顶级菜单项?
function jeMobileMenu( $args ) {
// Set up defaults arguments
$defaults = array (
\'menuSlug\' => \'\',
\'placeholder\' => \'Menu\',
\'prefix\' => \' » \',
\'navID\' => \'mobileNav\',
\'navClass\' => \'\'
);
// Parse incomming $args into an array and merge it with $defaults
$args = wp_parse_args( $args, $defaults );
//Declare each item in $args as its own variable i.e. $menuSlug, $placeholder
extract( $args, EXTR_SKIP );
// If no menu slug has been passed then lets bail
if ( empty($menuSlug) )
return;
// If the menu slug that has been passed doesn\'t correspond to an exisiting menu then lets bail
if ( !has_nav_menu( $menuSlug ) )
return;
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menuSlug ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
// Wrap the select in a nav element with passed id and classes
$menu_output = \'<nav id="\' . $navID . \'" class="\' . $navClass . \'">\';
$menu_output .= \'<select id="menu-\' . $menuSlug . \'" onchange="window.open(this.options[this.selectedIndex].value,\\\'_top\\\')">\';
// Add placeholder and home link
$menu_output .= \'<option value="">\' . $placeholder . \'</option>\';
$menu_output .= \'<option value="\' . home_url( \'/\' ) . \'">\' . $prefix . \'Home</option>\';
// Now loop through all the menu items and create them as options in the select list
foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
$menu_output .= \'<option value="\' . $url . \'">\' . $prefix . $title . \'</option>\';
}
$menu_output .= \'</select>\';
$menu_output .= \'</nav>\';
echo $menu_output;
}
最合适的回答,由SO网友:Brigante 整理而成
我想我解决了!!
我在每个$menu\\u项上进行了打印,看到其中有一个名为menu\\u item\\u parent的数组键。
所以我改变了这个:
foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
$menu_output .= \'<option value="\' . $url . \'">\' . $prefix . $title . \'</option>\';
}
对此:
foreach ( (array) $menu_items as $key => $menu_item ) {
if ( $menu_item->menu_item_parent == 0 ) :
$title = $menu_item->title;
$url = $menu_item->url;
$menu_output .= \'<option value="\' . $url . \'">\' . $prefix . $title . \'</option>\';
endif;
}
现在,它将只拉菜单项,而不拉菜单项父项。