Add .last class to menus

Adding this code to the functions.php file will append the class “last” to the last li tag outputed by wp_nav_menu. Very useful for when you need to style the last link in a drop down menu different from the others, or to remove that a separate after the last link in a horizontal menu.

// add the class 'last' to the last li elements in the menu navigation
add_filter('wp_nav_menu','add_last_item_class');
function add_last_item_class($menuHTML) {
  $last_items_ids  = array();

  // Get all custom menus
  $menus = wp_get_nav_menus();

  // For each menu find last items
  foreach ( $menus as $menu_maybe ) {

    // Get items of specific menu
    if ( $menu_items = wp_get_nav_menu_items($menu_maybe->term_id) ) {

      $items = array();
      foreach ( $menu_items as $menu_item ) {
		if ( !isset($items[$menu_item->menu_item_parent]) ) { $items[$menu_item->menu_item_parent] = array(); } // initilize array to avoid error messages
        $items[$menu_item->menu_item_parent][] .= $menu_item->ID;
      }

      // Find IDs of last items
      foreach ( $items as $item ) {
        $last_items_ids[] .= end($item);
      }
    }
  }

  foreach( $last_items_ids as $last_item_id ) {
    $items_add_class[] .= ' menu-item-'.$last_item_id;
    $replacement[]     .= ' menu-item-'.$last_item_id . ' last';
  }

  $menuHTML = str_replace($items_add_class, $replacement, $menuHTML);
  return $menuHTML;
}
Scroll to Top