4

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?

4

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;
}
|improve this answer|||||
0

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!

|improve this answer|||||
  • That would work. But why would you want that if; 1) php is faster and 2) more reliable js can be disabled. 3) (nitpick) increases page load. – janw Feb 18 '15 at 18:44
  • @janw Thanks for the feedback mate. I tried your solution but I kept getting this error: i.imgur.com/yuOAxIk.png I'm nowhere good with PHP, but I tried changing the string 'current-menu-ancestor' to 'current-page-ancestor' then to 'current-menu-item' (that might have just made it more wrong) to no avail. Here's how the code looks on my functions.php file: i.imgur.com/4rQh2wq.png Appreciate your help, and love your solution (wish I could get it to work on mine)! – Bibiano Wenceslao Feb 21 '15 at 1:51
0

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.

|improve this answer|||||

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.