Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.