Highlight parent menu item when child is not in menu

I want to highlight the parent of a child page in the menu when the child page itself is not in the menu.

I know this would work if you add the child as a sub page but that isn’t the case.

Any ideas?

Solutions Collecting From Web of "Highlight parent menu item when child is not in menu"

Alrdy got it:

<?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;
}

As an alternative to @janw’s answer, you can insert the following code in the theme’s footer.php file right before the closing body tag .

<!-- Highlight parent page link when on child page -->
<?php if (is_page()) {   //  displaying a child page ?>
    <script type="text/javascript">
        jQuery("li.current-page-ancestor").addClass('current-menu-item');
    </script>
<?php } ?>

I’ve detailed how this code works in a post here: How to keep parent page navigation link highlighted when viewing a child/sub page!

The accepted answer from @janw is very close, but get_post_anscestors() actually requires a WP Post or the ID of one as an argument per the WordPress docs:

https://developer.wordpress.org/reference/functions/get_post_ancestors/

I implemented like this and it works great:

function highlight_portfolio($classes, $item) {
    $parent = get_post_ancestors($item);
    $parent_ID = $parent[0];

    if ($parent_ID == $item->object_id) {
        array_push($classes, 'current-menu-ancestor');
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'highlight_portfolio', 12, 2);

I would just leave this as a comment but don’t have the reputation yet, so posting as an answer instead.