0

Here's the situation: In my main navigation menu I have something that looks like this:

  • Work with Me
    • Latest Projects

Where the Latest Projects page is a child page and sub menu item of the Work With Me page and both are displayed in the main navigation.

However, I have multiple Project pages that are only child pages of Latest Projects. I decided not to display them in the menu as sub menu items as the list would be too long.

So, what I would like to have happen is when a viewer is on one of the Project pages, both the Latest Projects and Work With Me menu items are active (highlighted).

I found this code to add to my functions.php file. It works, but it only highlights the Latest Projects menu item (not the Work With Me item).

<?php //in functions.php
add_filter('nav_menu_css_class', 'highlight_portfolio', 12, 2);
function highlight_portfolio($classes, $item) {
    $parent = get_post_ancestors();
    $parent_ID = $parent[0];
    if ($parent_ID == $item->object_id) {
        array_push($classes, 'current-menu-ancestor');
    }
    return $classes;
}

How can I modify this code to include all ancestor menu items? TIA!

1

You are checking against just one parent item.

Instead, you might check against all of the parents

<?php //in functions.php
add_filter('nav_menu_css_class', 'highlight_portfolio', 12, 2);
function highlight_portfolio($classes, $item) {
    $parents = get_post_ancestors();
    if ( 0 < count($parents) ) {
        if ( in_array( $item->object_id, $parents ) {
            array_push( $classes, 'current-menu-ancestor' );
        }
    }
    return $classes;
}

Notice in your code

$parent_ID = $parent[0];

That only grabs the first parent id in the list returned. Using in_array checks to see if it matches any of the ancestors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.