Site logo

[Resolved] How to set menu choice as current in certain pages

Home Forums Support [Resolved] How to set menu choice as current in certain pages

Home Forums Support How to set menu choice as current in certain pages

Viewing 3 posts - 31 through 33 (of 33 total)
  • Author
    Posts
  • #2497401
    David
    Staff
    Customer Support

    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 🙂

    #2497428
    Kirmo

    Wow, it works and more sophisticated & handy too, thanks.

    #2498589
    David
    Staff
    Customer Support

    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.

Viewing 3 posts - 31 through 33 (of 33 total)
  • You must be logged in to reply to this topic.