Skip to content

Instantly share code, notes, and snippets.

@petergus
Created July 4, 2012 17:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petergus/3048476 to your computer and use it in GitHub Desktop.
Save petergus/3048476 to your computer and use it in GitHub Desktop.
add first/last classes to wordpress wp_nav_menu
//an issue is that if the last li has children the last class will be applied to the last child.
// ===== option 1, not used ===== //
function add_first_and_last($output) {
$output = preg_replace('/class="menu-item/', 'class="first-menu-item menu-item', $output, 1);
$output = substr_replace($output, 'class="last-menu-item menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item'));
return $output;
}
add_filter('wp_nav_menu', 'add_first_and_last');
// ====== option 2, used ====== //
// This does the same actually, taken from http://css.dzone.com/news/wordpress-wpnavmenu-separator
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' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment