[wp-hackers] Adding class to first menu item of submenu in wp_nav_menu

Mike Schinkel mikeschinkel at newclarity.net
Sun Jun 27 22:46:54 UTC 2010


Hi Gavin,

There is the "nav_menu_css_class" filter hook which will allow you to do it but it will be a bit hackish. You are passed the existing CSS as well as the menu item but nothing that indicates the menu item's position.  You can access the items of the menu in the filter hook by retrieving them from the wp_get_nav_menu_items() function and then traversing the items to see if the item passed is "first" or not.  

If I were to do it I'd probably pre-process the list of items and create a global array keyed by item ids for only those that are "first." Then in the filter hook just use isset() on the indexed global array to determine if you should add "FIRST" to the CSS. (Of course, if you use the same menu items as submenus in multiple places it might be more difficult.)

Anyway, not elegant but except for the caveat it should probably get what you need.

HTH.

-Mike


On Jun 27, 2010, at 6:28 PM, Gavin Pearce wrote:

> Evening all,
> 
> Just wondering if any of you kind ladies and gentleman has found a way to add a "first" class, to the first item of each submenu within a menu generated by wp_nav_menu.
> 
> Adding a class to the first ever li is easy (preg_replace on menu-item x1), adding it to the first li "under" each and every submenu UL has confused me, without going into stupidly complex preg_replaces.
> 
> E.g.   (look for the FIRST's) ::
> 
> <ul>
> 	<li class="menu-item">Home</li>
> 	<li class="menu-item">Page1
> 		<ul class="submenu">
> 			<li class="FIRST menu-item">Subpage 1</li>
> 			<li class="menu-item">Subpage 2</li>
> 		</ul>
> 	</li>
> 	<li class="menu-item">Page3</li>
> 	<li class="menu-item">Page4
> 		<ul class="submenu">
> 			<li class="FIRST menu-item">Subpage 1</li>
> 			<li class="menu-item">Subpage 2</li>
> 		</ul>
> 	</li>
> </ul>
> 
> 
> Gav
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers



More information about the wp-hackers mailing list