I am a web developer and founder of Digimantra. I write and speak about latest web technologies and web trends. Sachin is a DZone MVB and is not an employee of DZone and has posted 19 posts at DZone. You can read more from them at their website. View Full User Profile

WordPress wp_nav_menu separator and First Last Classes

06.18.2011
| 6327 views |
  • submit to reddit

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

 

References
Published at DZone with permission of Sachin Khosla, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: