Advertisement
marjwyatt

Distinct Classes for WordPress Menu items with Last class

Jul 4th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.20 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Filters nav menu objects & items in your menus to add distinct custom classes to each item.
  5.  * Identifies last menu object and adds custom class for last item.
  6.  * @param object $objects An array of nav menu objects
  7.  * @param object $args Nav menu object args
  8.  * @return object $objects Amended array of nav menu objects with new class
  9.  * Original code: http://pastebin.com/WMhBfFqR - does not identify child elements correctly
  10.  * Working Solution Pastebin: http://pastebin.com/T0hr6sEx
  11.  */
  12.  
  13. add_filter( 'wp_nav_menu_objects', 'vm_filter_menu_classes', 10, 2 );
  14. function vm_filter_menu_classes( $objects, $args ) {
  15.  
  16.     if ( isset( $args->theme_location ) )
  17.         if ( 'primary' !== $args->theme_location ) // Only apply the classes to the primary navigation menu
  18.             return $objects;
  19.     $navObjects = wp_get_nav_menu_object( 'main' ); // this is the custom menu name
  20.     $objCount = $navObjects->count;
  21.     $i=0;
  22.     $navItems = wp_get_nav_menu_items( $navObjects ); //ref link: http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items
  23.     $navParentsArray = array ();
  24.     foreach($navItems as $navItem){
  25.         $i++; // increment counter
  26.         $itemID = $navItem->ID;
  27.         $itemTitle = $navItem->post_title;
  28.         $itemParent = $navItem->menu_item_parent;
  29.         $itemObjectID = $navItem->object_id;
  30.         $itemDB_ID = $navItem->db_id;
  31.         $itemPostName = $navItem->post_name; // returns page/post ID
  32.         if ( ( $itemParent == "0" )  ) {
  33.             $n=0;
  34.             $itemParents = $itemParents+1;
  35.             $saveParent = $itemDB_ID;
  36.             array_push($navParentsArray, $itemID);
  37.             $objects[$i]->classes[] = 'vm-parent-item-' . $i; // Add distinct class to menu parent objects
  38.             if ( $i == $objCount ) {
  39.                 $objects[$i]->classes[] = 'vm-last-menu-item'; // Add "last-menu-item" class to the last menu object
  40.             }
  41.         }
  42.         if ( ( $itemParent <> "0" )  ) {
  43.             $n=$n+1;
  44.             $objects[$i]->classes[] = 'vm-parent-' . $saveParent . '-child-' . $n; // Add distinct class to menu parent objects
  45.         }
  46.     } // end foreach
  47.     return $objects;
  48. } // end vm_filter_menu_classes
  49. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement