Я работаю над новым сайтом с пользовательским меню и расширенным классом Walker_Nav_Menu, чтобы добавить пользовательский контент в меню навигации wp.
я зарегистрировал пользовательский флажок (ключ: my_custom_menu) в меню от wordpress admin, посмотрите на следующее изображение:
Мой вопрос: есть ли способ удалить / исключить подменю, если пользователь использует настраиваемое меню вместо многоуровневого подменю, например:
//conditional for parent menu item Contact us if($menu_item->my_custom_menu !== 'none'){ //Remove all the nested submenu with depth != 0 (including <ul class="submenu">) // so the expecting result is : remove all submenus inside Contact us . }
Я знаю, что в классе Walker есть функция display_element (), но я не знаю, как ее использовать.
Фильтр «wp_nav_menu_objects» поможет:
add_filter( 'wp_nav_menu_objects', 'remove_sub_items', 10, 2 ); function remove_sub_items( $items,$args ) { $new_items = array(); for ($i=1;$i<count($items)+1;$i++){ //is lvl0 if(empty($items[$i]->menu_item_parent)){ $new_items= array_merge($new_items, nav_tree($items[$i],$items)); } } // var_dump($new_items); die(); if( $args->theme_location == 'primary' ) return $new_items; return $items; } function nav_tree($parent,$items){ $rtn = array(); $rtn[] = $parent; //Edit this conditional, return menu level 0 if has custom menu if($parent->my_custom_menu && $parent->my_custom_menu !== 'none') return $rtn; for ($i=1;$i<count($items)+1;$i++){ if($items[$i]->menu_item_parent && $items[$i]->menu_item_parent == $parent->ID) { $rtn= array_merge($rtn,nav_tree($items[$i],$items)); } } return $rtn; }
Просто вложенное меню на глубине 2, 3, 4 … идти, любая идея изменить петли? я изменил приведенный выше код, чтобы:
add_filter( 'wp_nav_menu_objects', 'remove_sub_items', 10, 2 ); function remove_sub_items( $items,$args ) { $new_items = array(); for ($i=1;$i<count($items)+1;$i++){ //is child if($items[$i]->menu_item_parent && $items[$i]->menu_item_parent != 0) { for ($j=1;$j<count($items)+1;$j++){ if($items[$j]->ID == $items[$i]->menu_item_parent && $items[$j]->my_custom_menu == 'none'){ $new_items[]=$items[$i]; } } } else{ $new_items[]=$items[$i]; } } //var_dump($new_items); die(); if( $args->theme_location == 'primary-menu-nav' ) return $new_items; return $items; }