Site logo

Archived topic

How to set menu choice as current in certain pages

32 replies · Started by Harris on October 2, 2017

Viewing posts 31–33 of 33

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.

This archived topic is closed to new replies.