How can I add a div around wordpress ul container
Asked Answered
T

2

5

Wordpress outputs my child menus inside this ul tag...

<ul class="sub-menu">

how can I wrap a simple div around it?

Preferably a way to do it through functions.php, but jquery can work too.

Tot answered 25/4, 2012 at 19:8 Comment(0)
S
17

While it would be EASY to use something like jQuery to wrap your child menus, it is NOT good practice to use jQuery for this purpose. Place this in functions.php:

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

I'm assuming that your menu is being generated in your header, so go to header.php (or whatever file is utilizing the wp_nav_menu function) and look for anything that starts with "wp_nav_menu".

Since I don't have any code to see, I can only guess the arguments that it's using (if any). If it looks EXACTLY like "wp_nav_menu()" with nothing in between the parenthesis, then change it to the following:

wp_nav_menu(array('walker' => new Child_Wrap()))

Otherwise, please edit your question with the code that your menu is using so I can help you further.

Striker answered 26/4, 2012 at 0:57 Comment(2)
Works Perfect (Wordpress 4.4 )Numerary
Why this does not work in v4.4.2? In my theme still without container of ul.sub-menu i got :(Prudenceprudent
P
1

In the function.php

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

Call to the function where your wp_nav_menu is located.(Ex: header.php)

$defaults = array( 'container' => 'ul', 'menu_class' => 'scroll', 'menu_id' => 'main-menu-nav' , 'walker' => new Child_Wrap() );

 wp_nav_menu( $defaults );

If you want to do this using jquery, you can do this as following.But best ways is first method.In here sometimes display as messed the menu when loading the page.

jQuery('ul.sub-menu').wrap('<div class="sub-menu-wrapper" />');
Prudhoe answered 9/9, 2013 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.