Skip to content

Instantly share code, notes, and snippets.

@thomasgriffin
Last active April 16, 2019 14:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasgriffin/4253190 to your computer and use it in GitHub Desktop.
Save thomasgriffin/4253190 to your computer and use it in GitHub Desktop.
<?php
add_filter( 'wp_nav_menu_objects', 'tgm_filter_menu_class' );
/**
* Filters the first and last nav menu objects in your menus
* to add custom classes.
*
* @since 1.0.0
*
* @param object $objects An array of nav menu objects.
* @return object $objects Amended array of nav menu objects with new class.
*/
function tgm_filter_menu_class( $objects ) {
// Add "first-menu-item" class to the first menu object.
$objects[1]->classes[] = 'first-menu-item';
// Add "last-menu-item" class to the last menu object.
$objects[count( $objects )]->classes[] = 'last-menu-item';
// Return the menu objects.
return $objects;
}
@grantpalin
Copy link

I can see this making nav styling easier in Internet Explorer 6-8 which don't support the first-child and last-child pseudo-elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment