Add last class to the wordpress menu items (nested list)

Some times you have to add "last" class for support old browsers and css. Add this snippet to your theme's function.php file and its done.


/**
 * Add classes to the menu items
 * http://php-everyday.blogspot.com
 */
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 ) {
        $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;

}
add_filter('wp_nav_menu','add_last_item_class');