Created
April 10, 2012 18:05
-
-
Save jeremyfelt/2353300 to your computer and use it in GitHub Desktop.
Strip whitespace between HTML tags in wp_nav_menu()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
Great idea @deweydb. Thanks! I ended up using '/li>\s+<li/'
as my regex to make sure I only removed spaces between <li>
s.
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 );
}
@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.
I believe the wp_nav_menu_items
filter can be used instead.
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
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: