wp_nav_menu add something before closing container and after last list item

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?

Solutions Collecting From Web of "wp_nav_menu add something before closing container and after last list item"

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( 
    esc_attr( $wrap_id ), 
    esc_attr( $wrap_class ), 

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.