Over a million developers have joined DZone.
Platinum Partner

WordPress wp_nav_menu separator and First Last Classes

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

wp_nav_menu is a wordpress built-in plugin that allows you to show navigation in the front-end. This simple function picks the menu defined in the wp-admin dashboard and displays it as the list. Just like other wordpress functions this is also powerful. It takes various parameters to customize the output of the navigation. You can also define menu separator using “link_before, link_after” or “before, after” params. But the common problem with this function is that you get a trailing separator.  As show in the example below -

Home | PHP | WordPress | CSS |

Of course you do not want the trailing “|“. Now let’s see how do we achieve this. Open the functions.php file the same file where you have registered this menu and paste the following function.

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

The above function adds a filter to the navigation such that the first navigation gets a class menu-item-first and the last menu item gets the class menu-item-last assigned. Now all you have to do is to include the necessary CSS style to make it invisible. To do so, simply add the following style information into your CSS stylesheet file, usually styles.css

.menu-item-last {
display: none;

So that way you can have the awesome navigation without that annoying trailing separator. Hope that helps !

Stay Digified !!
Sachin Khosla


The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Sachin Khosla , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}