1

I've been looking for a way to hard code a <div> tag before the closing container tag of a particular menu:

$footer_nav = array(
    'menu'              => 'footer-menu',
    'menu_class'        => 'foobar',
    'container'         => 'ul',
    'theme_location'    => 'footer',
    'menu_id'           => 'footer_menu',
    'echo'              => true,
    'depth'             => 1,
);
wp_nav_menu( $footer_nav );

However when I try to add:

'after' => '<div class="foo">bar</div>',

it adds it after every list item. When I researched for a solution I ran across I want remove last after wp_nav_menu and Wordpress Functions - How to use Replace String func. to add some code but when I try:

function foobar_the_menu($items,$args) {
    if ($args->theme_location == 'footer') {
        $footer_pattern     = '</li></ul>';
        $footer_replacement = '</li><div class="foo">bar</div></ul>';
        return substr_replace( $footer_pattern, $footer_replacement, $items, 1 );
    }
}
add_filter( 'wp_nav_menu', 'foobar_the_menu', 10, 2 );

It removes all the menus. After referencing a few other questions I did see wp_nav_menu_items and preg_replace but I'm unsure what is the correct approach to target a particular menu to hard code a div since you cannot modify this in the menu array?

1 Answer 1

2

I think you can use:

'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s <div class="foo">bar</div> </ul>',

as a wp_nav_menu() argument.

We're using this part of the wp_nav_menu() function:

$nav_menu .= sprintf( 
    $args->items_wrap, 
    esc_attr( $wrap_id ), 
    esc_attr( $wrap_class ), 
    $items 
);

where the items_wrap argument contains the following sprintf specifiers:

  • %1$s to match the wrap id
  • %2$s to match the wrap class
  • %3$s to match the generated HTML for the items.
3
  • That worked, do you mind explaining what %1$s, %2$s and %3$s are doing so I can understand the solution better?
    – user9447
    Oct 15, 2016 at 14:08
  • 1
    Great, sure I updated the answer @DᴀʀᴛʜVᴀᴅᴇʀ
    – birgire
    Oct 15, 2016 at 14:40
  • 1
    Thanks, I figured that could help someone in the future know what is going on, +1
    – user9447
    Oct 15, 2016 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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