CSS: Add first and last menu item class to menus

Navigation menus are important part any website. If you want to apply a css class to the first and last part of menu item then here is the code snippet.

Add following code to “functions.php”


add_filter('wp_nav_menu', 'add_first_last_menu_classes');
function add_first_last_menu_classes($output) {
    $output= preg_replace('/menu-item /', 'first-menu-item menu-item ', $output, 1);
	$output=substr_replace($output, "last-menu-item menu-item", strripos($output, "menu-item"), strlen("menu-item"));
    return $output;

CSS Snippet

Same thing can also be achieved using css pseudo code snippet

  /*place css here for first item*/
  /*place css here for last item*/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>