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 :)