I would like to add the CSS class of the current menu item (and the classes of its parents & ancestors) to the current page body classes.
For example, if the current menu item has a CSS class “products” (as defined in Appearance | Menus), then the body for the corresponding page should also have the class “products”.
If that makes sense to anyone, any ideas how to do it?
I’ve looked at “How to add current, parent, and ancestor menu item IDs to body_class()?” but can’t get those ideas to work in my case.
This is what I managed to cobble together thanks to Mridul Aggarwal’s hints:
This function does a little too much, because it adds all the
menu-item
-type classes too. All I really want is the custom CSS classes which the user has entered into the CSS Classes field in the WordPress menus admin screen. Any thoughts on how to extract only those classes would be most welcome.In the answer
you linked
, do avar_dump($dosmenu);
just above the line_wp_menu_item_classes_by_context( $dosmenu );
. That variable should be already initialised with the classes you want.After that you can adapt the
foreach
loop accordingly & use that function as a filter tobody_class
.The classes set in the admin are stored as a post meta with key
_menu_item_classes
which are automatically initialised in the call towp_get_nav_menu_items
Slight alteration to your code posted above to get only custom class.
The custom class is always the first item.
EDIT: This and the original filter replace the default classes though. If you just want to add them…