在我的wordpress网站中,我正在自定义菜单。因为我使用此代码获取所有菜单项
`<?php$menu_name = 'hamburger-menu';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);$output = '<ul>';
foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$output.='<li>'.$title.'</li>';
print_r($menu_item);
}
$output.='</select>';
}
echo $output;
?>`
此代码逐个打印所有菜单项和子菜单项
`<ul>
<li>Menu Item</li>
<li>Menu Item</li>
<li>Drinks</li>
<li>Sub menu item</li>
<li>Menu Item</li>
<li>Sub menu item</li>
<li>Sub menu item</li>
<li>Menu Item</li>
</ul>`
但我想要这样的输出
`<ul>
<li>Menu Item</li>
<li>Menu Item</li>
<li>Menu Item
<ul><li>Sub menu item</li></ul>
</li>
<li>Menu Item
<ul>
<li>Sub menu item</li>
<li>Sub menu item</li>
</ul>
</li>
<li>Menu Item</li>
</ul>`
可以帮助任何人
答案 0 :(得分:1)
示例1:
$resultMainMenu = mysql_query("SELECT * FROM tblmenu WHERE parentid=0 ORDER BY menuname ASC") or die(mysql_error());
while($row = mysql_fetch_array($resultMainMenu)){
echo $row['menutitle'] . '<br />'; // echo main menu
$resultSubmenu = mysql_query("SELECT * FROM tblmenu WHERE parentid=" . $row['id'] . " ORDER BY menuname ASC") or die(mysql_error());
if(mysql_num_rows($resultSubmenu) >= 1){
while($rowSub = mysql_fetch_array($resultSubmenu)){
echo ' -- ' . $rowSub['menutitle'] . '<br />'; // echo sub menu
}
}
}
示例2:
function display_children($parent, $level) {
$result = mysql_query("SELECT a.id, a.label, a.link, Deriv1.Count FROM `menu` a LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `menu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent=" . $parent);
echo "<ul>";
while ($row = mysql_fetch_assoc($result)) {
if ($row['Count'] > 0) {
echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a>";
display_children($row['id'], $level + 1);
echo "</li>";
} elseif ($row['Count']==0) {
echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a></li>";
} else;
}
echo "</ul>";
}
你可以按照你的要求放置条件