How can I add a div around wordpress ul container

WordPress outputs my child menus inside this ul tag…

<ul class="sub-menu">

how can I wrap a simple div around it?

Read More

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

Related posts

Leave a Reply

2 comments

  1. 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.

  2. 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" />');