Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've tried to hook wp_nav_menu_args to get an ID for the nav menu. I tried to add an element using javascript to container menu. But I never get the ID for the menu.

How can I add an element to a nav menu container from:

<nav id="my-menu"><ul><li>.....<li></ul></nav>

to:

<nav id="my-menu"><div class="additional"></div><ul><li>.....<li></ul></nav>
share|improve this question
add comment

1 Answer 1

This is fairly straightforward, assuming you have access to the php files.

In the template that generates the menu, modify the wp_nav_menu call to specify container = FALSE, and to provide the container and additional div manually in the surrounding HTML.

Without knowing your code in advance, one method would be to alter it as follows:

<nav id="my-menu"><div class="additional"></div>
    <?php 
        // Replicate the args from the original code for the most part
        $args = array(
            'theme_location' => 'primary', // Or whatever the original was
            'container'      => FALSE, // This tells it to not put a container around it
            'echo'           => TRUE, // again, whatever original was
            // .. any other args from original code ...
        );
        wp_nav_menu($args);
    ?>
</nav>

EDIT: Knowing that the menu needs to be modified at generation, then the answer changes a bit:

You need to create a custom menu walker

Fundamentals below. Modify based on your needs, reference the Walker article above:

class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
  function start_el ( &$output, $item, $depth = 0, $args = array(), $id = 0 )     {
    // Copy all the start_el code from source, and modify
  }

  function end_el( &$output, $item, $depth = 0, $args = array() ) {
    // Copy all the end_el code from source, and modify
  }
}

Then, in your theme files, you can call wp_nav_menu like this:

wp_nav_menu(array(
  'theme_location' => 'main',
  'container' => false,
  'menu_id' => 'nav',
  'depth' => 1,
  // This one is the important part:
  'walker' => new Custom_Walker_Nav_Menu
));
share|improve this answer
    
Hi @cale_b. Thanks for your response. Actually i need to modify nav menu when it generated because i have many menus. I have setting page at dashboard to determine which menu need to add this div element. Can U give me another idea? –  user1841035 Jun 5 at 2:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.