I've searched for hours and cannot come up with what I thought would be a simple thing. I am building my very first Wordpress site locally. I'm making a function for my functions.php file based on this howto but I need it to have submenus. I have created a custom menu inside Wordpress with 2 levels.
I need to add HTML code (not a CSS class) to an item if it is a parent item.
Bonus points if you can tell me how people know what attributes/properties are available to a menu item (such as title and url) - I can't find a reference to that anywhere!
Here is my current code, which is currently displaying all menu items as top-level items.
function clean_custom_main_menu() {
$menu_name = 'main-menu'; // specify custom menu slug
$menu_list = '<ul id="menu">' ."\n";
if ($menu_items = wp_get_nav_menu_items($menu_name)) {
$count = 0;
$submenu = false;
foreach ((array) $menu_items as $key => $menu_item) {
$title = $menu_item->title;
$url = $menu_item->url;
$classes = $menu_item->classes; // does not work
$has_children = $menu_item->has_children; //does not work
$parent_id = 0;
// check if this item is a parent item with children
//if ( $menu_item->menu_item_parent && $menu_item->menu_item_parent > 0 ) {
//if(in_array('menu-item-has-children', $classes)){
if ($has_children) {
$parent_id = $menu_item->ID;
}
// if this item has a parent ID, it's a second-level item
if ($parent_id != 0 && $parent_id == $menu_item->menu_item_parent ) {
$submenu = true;
}
if (!$has_children) {
// if this item has no submenu, write top-level code
$menu_list .= "\t". '<li><a href="'. $url .'">'. $title .'</a></li>' ."\n";
}
// the "else" is not currently being hit
//else {
// $menu_list .= "\t" . '<li><a href="#">' . $title . '<span class="arrow-down"></span></a></li>' . "\n";
// $menu_list .= '<ul class="sub">';
// // foreach (child) do children
// $menu_list .= '</ul>';
// $menu_list .= '</li>';
//}
}
} else {
$menu_list .= '<!-- no list defined -->';
}
$menu_list .= "\t". '</ul>' ."\n";
echo $menu_list;
}
Desired output:
<ul id="menu">
<li><a href="#">Home</a></li>
<li>
<a href="#">About <span class="arrow-down"></span></a>
<ul class="sub">
<li><a href="/about/services.html">Our Services</a></li>
<li><a href="/about/what-we-do.html">What We Do</a></li>
</ul>
</li>
<li>
<a href="/top-level-item/">Top-Level Item</a>
</li>
<li><a href="#">Top-Level Item with Children <span class="arrow-down"></span></a>
<ul class="sub">
<li><a href="/top-level-item2/item1">Sub Item 1</a></li>
<li><a href="/top-level-item2/item2">Sub Item 2</a></li>
<li><a href="/top-level-item2/item3">Sub Item 3</a></li>
<li><a href="/top-level-item2/item4">Sub Item 4</a></li>
</ul>
</li>
<li><a href="/contact/">Contact</a></li>
</ul>
Please note: I do not want to use walkers. I am certain it can be done somehow since I had this working at one point, but lost everything when Wordpress decided to update the theme I made - to a totally different one from web-land, erasing all my files. D'oh!