How to Wrap a Wordpress Sub menu with DIV

When you are Converting HTML to Wordpress you are oftentimes suffer from this.
The Sub menu of your main navigation containing <div> wrapper in your sub menu (Second Level Menu).



Here is the Solutions , You Have Just add Some Code in Your function.php File and Set Walker parameter for your wp_nav_menu() tag.

eg.
<ul class="menu">
<li><a href="#">Home</a></li>
<li><a href="#">Home</a>
<div>
<ul class="submenu">
<li><a href="#">Sub Menu1</li>
<li><a href="#">Sub Menu2</li>
<li><a href="#">Sub Menu3</li>
</ul>
</div>
</li>
</ul>

Here Child Navigation Contain div Wrapper. How Can We Handle this with Wordpress Menu.

Add Following Lines in Your function.php File


class Child_Wrap extends Walker_Nav_Menu
{
   
function start_lvl(&$output, $depth)
   {
       $indent = str_repeat(
"\t", $depth);
       $output .=
"\n$indent<div class=\"custom-sub\"><ul class=\"sub-menu\">\n";
   }
   
function end_lvl(&$output, $depth)
   {
       $indent = str_repeat(
"\t", $depth);
       $output .=
"$indent</ul></div>\n";
   }
} 

Now Just Set Your Menu Walker. From Your Header.php file where your wp_nav_menu is located.



  <?php

$defaults = array(
'theme_location'  => '',
'container'       => 'div',
'container_class' => '',
'container_id'    => '',
'menu_class'      => 'menu',
'echo'            => true,
'fallback_cb'     => 'wp_page_menu',
'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth'           => 0,
'walker'          => new Child_Wrap()
);

wp_nav_menu( $defaults );

?>                               



Thats All,

Now you can see Your submenu is wrapped with div tag.

Comments

  1. Amazing information about Open Source Development Services. Open Source Development is best way to increase your online business through attractive website. We have total solution for open source development like Magento, WordPress, Drupal, Zen Cart and many more.

    ReplyDelete
  2. Hey.. you have solved my problem... I'm self-taught webdesigner...and fought for almost one weak for this solution (visited 50+ pages via google).. but proudly your solution worked...

    ReplyDelete
  3. Didn't work for me. I think I have the functions.php right but maybe my array is wrong. when I call the walker from my header none of my submenu items appear at all.

    ReplyDelete
  4. Its related to a plugin I'm using, jc_submenu, it generates submenu items from posts, i'll take a look see why it's not working.

    ReplyDelete
  5. Got it, the developer of the plugin added a filter that allows compatibility with custom walkers and the plugin. Perfect. By the way, check out this plugin it's really great. Allowed me to have menus that automatically populate based off category posts.

    http://jamescollings.co.uk/docs/v1/jc-submenu/how-tos/enable-menu-walker-compatability/

    ReplyDelete

Post a Comment