WordPress Tricks #2

The problem

This is more of a workaround, than an actual trick: when using the new custom menus in WordPress 3 < ?php wp_nav_menu(&args); ?> , how to add a separator after each menu item, without it being shown also after the last item.

In other words: Link 1 | Link 2 | Link 3 | no one wants that last separator at the end of the menu, but WordPress hasn’t sorted that out yet.

The fix

First of all add this to your functions.php:

function nav_menu_first_last( $items ) {
$position = strrpos($items, 'class="menu-item', -1);
$items=substr_replace($items, 'menu-item-last ', $position+7, 0);
$position = strpos($items, 'class="menu-item');
$items=substr_replace($items, 'menu-item-first ', $position+7, 0);
return $items;
}
add_filter( 'wp_nav_menu_items', 'nav_menu_first_last' );
}

What this function will do, is to simply add 2 new classes, one for the first menu item menu-item-first and one for the last item menu-item-last.

Then just go ahead and add the wp menu function, adding the argument after and the type of separatore you want (in this case | ), surrounded by a simple span:

<?php wp_nav_menu(array('menu' => 'Bottom', 'menu_class' => 'bottom-menu', 'after' => '<span> | </span>')); ?>

Finally, to get rid of the last separator, add this rule to your style.css:

.menu-item-last span {
display: none;
}

Problem fixed :)

Jany Martelli · Shambix

Written by the Shambix engineering team: custom apps, AI agents, WordPress & WooCommerce, cloud and private AI since 2009.

Jany Martelli builds the systems behind digital businesses: cloud architecture, e-commerce platforms, and AI agents that do real work. 17+ years and 250+ projects at Shambix, for teams from Xiaomi to Hilton. Computer scientist, professor, and creator of Patcherly, the AI that fixes production bugs on its own.

Custom Apps

Have a project in mind? Let's build it right.

Tell us about your goals and your budget. From a quick WordPress fix to a full custom platform, we’ll take care of the rest.

  • A senior engineer reads every brief
  • If we are not the right fit, we say so
  • info@shambix.com
Name

We usually reply within 24 hours. No newsletter, no spam.