我正在尝试使用wp_get_nav_menu_items函数在WordPress中显示3级层次菜单, 但是以某种方式未显示结构。
这是我包含在头文件中的代码, 但是结构不正确。
$menu_name = 'primary-menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menuitems = wp_get_nav_menu_items($menu->term_id, array('order' => 'DESC'));
$ParentArray = array();
foreach ($menuitems as $item) {
// if (!empty($item->menu_item_parent) && !in_array($item->menu_item_parent, $ParentArray)) {
array_push($ParentArray, $item->ID);
// }
}
?>
<nav>
<ul class="main-nav">
<?php
$count = 0;
$submenu = false;
foreach ($menuitems as $item):
$link = $item->url;
$title = $item->title;
// item does not have a parent so menu_item_parent equals 0 (false)
if (!$item->menu_item_parent):
// save this id for later comparison with sub-menu items
$parent_id = $item->ID;
?>
<li class="item">
<a href="
<?php echo $link; ?>" class="title">
<?php echo $title; ?>
</a>
<?php endif; ?>
<?php if (in_array($item->menu_item_parent, $ParentArray)): ?>
<?php if (!$submenu): $submenu = true; ?>
<ul class="sub-menu">
<?php endif; ?>
<li class="item">
<a href="
<?php echo $link; ?>" class="title">
<?php echo $title; ?>
</a>
</li>
<?php if (!isset($menuitems[$count + 1]) || $menuitems[$count + 1]->menu_item_parent != $parent_id && $submenu): ?>
</ul>
<?php
$submenu = false;
endif;
?>
<?php endif; ?>
<?php if (!isset($menuitems[$count + 1]) || $menuitems[$count + 1]->menu_item_parent != $parent_id): ?>
</li>
<?php
$submenu = false;
?>
<?php
$count++;
endforeach;
?>
</ul>
</nav>
#1
在上面的代码中进行更改后, 这件事对我有用。
$menu_name = 'primary-menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menuitems = wp_get_nav_menu_items($menu->term_id, array('order' => 'DESC'));
$ParentArray = array();
foreach ($menuitems as $item) {
// if (!empty($item->menu_item_parent) && !in_array($item->menu_item_parent, $ParentArray)) {
array_push($ParentArray, $item->ID);
// }
}?>
<nav>
<ul class="main-nav">
<?php
$count = 0;
$submenu = false;
foreach ($menuitems as $item):
$link = $item->url;
$title = $item->title;
// item does not have a parent so menu_item_parent equals 0 (false)
if (!$item->menu_item_parent):
// save this id for later comparison with sub-menu items
$parent_id = $item->ID; ?>
<li class="item">
<a href="
<?php echo $link; ?>" class="title">
<?php echo $title; ?>
</a>
<?php endif; ?>
<?php if (in_array($item->menu_item_parent, $ParentArray)): ?>
<?php if (!$submenu): $submenu = true; ?>
<ul class="sub-menu">
<?php endif; ?>
<li class="item">
<a href="
<?php echo $link; ?>" class="title">
<?php echo $title; ?>
</a>
</li>
<?php if (!isset($item[$count + 1]) || $item[$count + 1]->menu_item_parent != $parent_id && $submenu): ?>
</ul>
<?php
$submenu = false;
endif;
?>
<?php endif; ?>
<?php if (!isset($menuitems[$count + 1]) || $menuitems[$count + 1]->menu_item_parent != $parent_id): ?>
</li>
<?php
$submenu = false;
?>
<?php
$count++;
endforeach;
?>
</ul>
</nav>
评论前必须登录!
注册