我正在为WordPress项目创建自定义菜单。我使用以下函数clean_custom_menus()
清理了菜单的标记。我目前遇到的问题是如果它有一个父菜单项,就会弄清楚如何向#menu_item
添加一个类。我的菜单设置如下:
我从代码的角度来看,我需要检查$menu_item
是否有孩子。从查看WordPress文档,我看到有一个名为$has_children
的函数。但我不知道确切的语法。任何帮助将不胜感激。
在我的 functions.php
中// custom menu example @ https://digwp.com/2011/11/html-formatting-custom-menus/
function clean_custom_menus() {
$menu_name = 'primary'; // specify custom menu slug
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);
$menu_list = '<nav role="navigation">' ."\n";
$menu_list = '<div class="nav-wrapper">' . "\n";
$menu_list .= "\t\t\t\t". '<ul id="nav-mobile" class="left hide-on-med-and-down">' ."\n";
foreach ((array) $menu_items as $key => $menu_item) {
$title = $menu_item->title;
$url = $menu_item->url;
//I would like to add a class to the li if it has a parent
$menu_list .= "\t\t\t\t\t". '<li><a href="'. $url .'">'. $title .'</a></li>' ."\n";
}
$menu_list .= "\t\t\t\t". '</ul>' ."\n";
$menu_list .= "\t\t\t\t". '</div>' ."\n";
$menu_list .= "\t\t\t". '</nav>' ."\n";
} else {
// $menu_list = '<!-- no list defined -->';
}
echo $menu_list;
}
EDITED
这是我更新的 functions.php
// custom menu example @ https://digwp.com/2011/11/html-formatting-custom-menus/
function clean_custom_menus() {
$menu_name = 'primary'; // specify custom menu slug
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);
$menu_list = '<div class="nav-wrapper">' . "\n";
$menu_list .= "\t\t\t\t". '<ul id="nav-mobile" class="left hide-on-med-and-down">' ."\n";
foreach ((array) $menu_items as $key => $menu_item) {
$title = $menu_item->title;
$url = $menu_item->url;
if ( $menu_item->post_parent != 0 ) {
$menu_list .= "\t\t\t\t\t". '<li class="dropdown"><a href="'. $url .'">'. $title .'</a></li>' ."\n";
}
else {
$menu_list .= "\t\t\t\t\t". '<li><a href="'. $url .'">'. $title .'</a></li>' ."\n";
}
}
$menu_list .= "\t\t\t\t". '</ul>' ."\n";
$menu_list .= "\t\t\t\t". '</div>' ."\n";
} else {
// $menu_list = '<!-- no list defined -->';
}
echo $menu_list;
我的问题是如何在if语句(if ( $menu_item->post_parent != 0 )
)中更改逻辑,以便将子菜单放在<ul>
?
这是当前标记的样子:
<ul>
<li>Menu</li>
<li class="dropdown">Sub Item</li>
<li class="dropdown">Sub Item</li>
<li class="dropdown">Sub Item</li>
<li>Menu</li>
...
</ul>
这就是我希望标记的方式:
<ul>
<li>Menu</li>
<li>
<a class="dropdown-button" href="#!" data-activates="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a>
<ul id="dropdown1" class="dropdown-content">
<li><a href="#!">one</a></li>
<li><a href="#!">two</a></li>
<li class="divider"></li>
<li><a href="#!">three</a></li>
</ul>
</li>
...
</ul>
我认为逻辑将是if循环或if语句中的另一个foreach循环。
答案 0 :(得分:0)
这会有帮助吗?
if ( $menu_item->post_parent != 0 ) {
// yout post has a parent
}