Archived topic
How to set menu choice as current in certain pages
32 replies · Started by Harris on October 2, 2017
OK, try adding this PHP Snippet:
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
function add_menu_parent_class( $items ) {
$parents = array();
foreach ( $items as $item ) {
if ( in_array('current-page-ancestor', $item->classes) ) {
$parents[] = $item->menu_item_parent;
}
}
foreach ( $items as $item ) {
if ( in_array( $item->ID, $parents ) ) {
$item->classes[] = 'current-menu-ancestor';
}
}
return $items;
}
If that works it should add the current-menu-ancestor class to the top level item.
Let me know :)
Wow, it works and more sophisticated & handy too, thanks.
Glad to be of help!
For reference i saved the snippet in this GIST:
https://gist.github.com/diggeddy/dcfb6a55c9537eb1c233b7b1069b9af2
BUT it not only checks for pages, it will check for posts in a similar scenario eg. Posts in specific Categories that are listed a sub menu.