public
Last active

  • Download Gist
gistfile1.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
add_filter( 'wp_nav_menu_objects', 'tgm_filter_menu_class', 10, 2 );
/**
* Filters the first and last nav menu objects in your menus
* to add custom classes.
*
* This also supports nested menus.
*
* @since 1.0.0
*
* @param array $objects An array of nav menu objects
* @param object $args Nav menu object args
* @return object $objects Amended array of nav menu objects with new class
*/
function tgm_filter_menu_class( $objects, $args ) {
 
// Add first/last classes to nested menu items
$ids = array();
$parent_ids = array();
$top_ids = array();
foreach ( $objects as $i => $object ) {
// If there is no menu item parent, store the ID and skip over the object
if ( 0 == $object->menu_item_parent ) {
$top_ids[$i] = $object;
continue;
}
 
// Add first item class to nested menus
if ( ! in_array( $object->menu_item_parent, $ids ) ) {
$objects[$i]->classes[] = 'first-menu-item';
$ids[] = $object->menu_item_parent;
}
 
// If we have just added the first menu item class, skip over adding the ID
if ( in_array( 'first-menu-item', $object->classes ) )
continue;
 
// Store the menu parent IDs in an array
$parent_ids[$i] = $object->menu_item_parent;
}
 
// Remove any duplicate values and pull out the last menu item
$sanitized_parent_ids = array_unique( array_reverse( $parent_ids, true ) );
 
// Loop through the IDs and add the last menu item class to the appropriate objects
foreach ( $sanitized_parent_ids as $i => $id )
$objects[$i]->classes[] = 'last-menu-item';
 
// Finish it off by adding classes to the top level menu items
$objects[1]->classes[] = 'first-menu-item'; // We can be assured 1 will be the first item in the menu :-)
$objects[end( array_keys( $top_ids ) )]->classes[] = 'last-menu-item';
 
// Return the menu objects
return $objects;
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.