WordPress Tips: How to remove the extra space between LI elements from wp_nav_menu

Here is the snippet of code I use to remove the extra space that WordPress adds to the end of

  • elements when you use wp_nav_menu to call in a menu:

    <?php $custommenu = wp_nav_menu ( array (
    		'container_class' => 'my-menu',
    		'theme_location' => 'primary',
                    'echo'            => 0
     ) );
    $custommenu = str_replace("\n", "", $custommenu);
    $custommenu = str_replace("\r", "", $custommenu);
    echo $custommenu;
    ?>

    Meet the author

    Libby Fisher is an experienced freelance web developer, recently relocated from Seattle to Boston, and passionate about developing websites that are both aesthetically appealing and intuitively usable - or as she prefers: "beautifully effective."

    • Jake

      I would suggest shortening the syntax for modern php:
      echo str_replace(["n", "r"], "", $custommenu);Also there is a filter wp_nav_menu_items for filtering the menu output,
      so you don’t need to do this everytime you call wp_nav_menu :) :
      add_filter( 'wp_nav_menu_items', function ( $items, $args = [] ){
      return str_replace(["n", "r"], "", $items);
      });
      If your menu output contains more white space (not just line breaks) like spaces etc… then you need to use preg_replace instead of str_replace:
      preg_replace( '/>(s|n|r)+<', $items );…this replaces all white space and line breaks between tags, which is usually what you need (in 99% cases).

      preg_replace is slower than str_replace so I recommend to use it only if you really need to…