0
I want to build a menu in Wordpress with 3 levels.
This example has 2 levels, the father and the son.
I want the menu to have one more level, so I can create a 3-level menu with Wordpress.
Below, on the left, a code that refers to two menu levels.
Example of the menu in this Link
<?php
$menu_name = 'main_nav';
$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' ) );
?>
<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 ( $parent_id == $item->menu_item_parent ): ?>
<?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 ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id && $submenu ): ?>
</ul>
<?php $submenu = false; endif; ?>
<?php endif; ?>
<?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id ): ?>
</li>
<?php $submenu = false; endif; ?>
<?php $count++; endforeach; ?>
</ul>
</nav>
It would be interesting to put the CSS, although the subject is Wordpress. So can get an answer more easily.
– Sam
So CSS wouldn’t be important, just put the structure in to be able to make a 3-level menu. It can be a simple structure of <ul><li> </li> </ul> . I got a good solution I’ll post here.
– Felipe Jorge
In case this would be a code to simplify the programming of Wordpress, which to create menus without plugins is very confusing and not from the support for menus of 3 levels. I managed to apply a solution.
– Felipe Jorge
If anyone has a better solution, please post the reward.
– Felipe Jorge
The advantage of using the menu this way is that you can use the HTML structure you want. Unlike the function of native Wordpress that often you can not make a mega menu or a menu with more complex programming.
– Felipe Jorge