Skip to content

Instantly share code, notes, and snippets.

@illucent
Created March 8, 2014 13:34
Show Gist options
  • Select an option

  • Save illucent/9430689 to your computer and use it in GitHub Desktop.

Select an option

Save illucent/9430689 to your computer and use it in GitHub Desktop.
first and last wordpress menu item
function add_menu_parent_class( $items ) {
// GET PARENT ITEMS
$parents = array();
foreach ( $items as $item ) {
if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {
$parents[] = $item->menu_item_parent;
}
}
// COUNT PARENT ITEMS
$count = 0;
foreach ( $items as $item ) {
if (in_array( $item->ID, $parents )) {
$count++;
}
}
// ADD CLASSES TO FIRST AND LAST PARENT LI TAGS
$i = 1;
foreach ( $items as $item ) {
if ( in_array( $item->ID, $parents ) ) {
if ($i == 0) {
$item->classes[] = 'first-menu-parent-item';
}
if ($i == $count) {
$item->classes[] = 'last-menu-parent-item';
}
$i++;
}
}
return $items;
}
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment