Advertisement
marjwyatt

add css classes to wordpress menu objects

Aug 3rd, 2013
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.46 KB | None | 0 0
  1. /**
  2.  * Filters the first and last nav menu objects in your menus to add custom classes.
  3.  * @param object $objects An array of nav menu objects
  4.  * @param object $args Nav menu object args
  5.  * @return object $objects Amended array of nav menu objects with new class
  6.  * ref link: http://thomasgriffinmedia.com/blog/2012/12/how-to-add-custom-classes-first-last-menu-items-wordpress/
  7.  * Augmented Griffin's code with while and if loops to assign distinct css class to each menu item by Virtually Marj http://virtuallymarj.com
  8.  * While my project only required classes for the primary menu, this code could be embellished to address any menu location or menu in your theme
  9.  */
  10. add_filter( 'wp_nav_menu_objects', 'vm_filter_menu_class', 10, 2 );
  11. function vm_filter_menu_class( $objects, $args ) {
  12.  
  13.     if ( isset( $args->theme_location ) )
  14.         if ( 'primary' !== $args->theme_location ) // Only apply the classes to the primary navigation menu
  15.             return $objects;
  16.     $navitems = wp_get_nav_menu_object( 'main' ); // this is the custom menu name
  17.     $navcount = $navitems->count;
  18.     $i=1;
  19.     while ( $i <> $navcount ) {
  20.     // Add distinct class to menu objects
  21.         $objects[$i]->classes[] = 'images-menu-item-' . $i;
  22.         $i++;
  23.         }
  24.  
  25.     // Add "last-menu-item" class to the last menu object
  26.     if ( $i == $navcount ) {
  27.         $objects[count( $objects )]->classes[] = 'last-menu-item';
  28.     }
  29.  
  30.     // Return the menu objects
  31.     return $objects;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement