Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jeremyfelt
Created April 10, 2012 18:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyfelt/2353300 to your computer and use it in GitHub Desktop.
Save jeremyfelt/2353300 to your computer and use it in GitHub Desktop.
Strip whitespace between HTML tags in wp_nav_menu()
<?php
/* Modify the output of list items in the header navigation menu.
*
* Remove the whitespace between HTML tags. Required specifically for better
* behavior when list items are inline-block in our main nav menu and need
* the browsers to adhere to exact margins.
*
* NOTE: filter name changes depending on your menu - this one works for 'navigation_items'
*/
add_filter( 'wp_nav_menu_header-navigation_items', 'prefix_remove_menu_item_whitespace' );
function prefix_remove_menu_item_whitespace( $html_content ) {
return preg_replace( '/>\s+</', '><', $html_content );
}
@deweydb
Copy link

deweydb commented Jun 17, 2013

This didn't work for me. I can't find any documentation anywhere other than this gist that that filter even exists. Maybe this is outdated?

Edit: for others stuck on this, my solution (a little bit hacky) was to use this regext, and just return the wp_nav_menu directly into it, then print that out, eg:

     echo preg_replace( '/>\s+</', '><', wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary', 'echo'=>0 ) ) ); 

@colllin
Copy link

colllin commented Aug 17, 2013

Great idea @deweydb. Thanks! I ended up using '/li>\s+<li/' as my regex to make sure I only removed spaces between <li>s.

@vasilake-v
Copy link

Good !
You can use the filter wp_nav_menu_items, for any menu. And take care of new lines also using the />(\s|\n|\r)+</ regexp

add_filter( 'wp_nav_menu_items', 'prefix_remove_menu_item_whitespace' );
function prefix_remove_menu_item_whitespace( $items, $args ) {
    return preg_replace( '/>(\s|\n|\r)+</', '><', $items );
}

@cramdesign
Copy link

@slava-v, I get an error: "Missing argument 2 for prefix_remove_menu_item_whitespace()..."

Remove the second parameter and it works like a charm. Thanks.

@To-mos
Copy link

To-mos commented Jan 9, 2017

I believe the wp_nav_menu_items filter can be used instead.

@RadGH
Copy link

RadGH commented Mar 22, 2018

Now a better option is to add the argument 'item_spacing' => 'discard'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment