How to set the currently active page in the menu including parents

I have the following problem:

There is a custom post type. There are several pages each listing some of the posts based on some post criteria (custom WP_Query).

When I click on a link to open the full version of the post, the parent page of the post is . But for the sake of user experience it should be the parent page the user came from and that should be highlighted in the menu.

I partly solved this problem by adding “?parent=” to the links and parsing that in a filter:

// Fix menu parents
add_filter(‘nav_menu_css_class’, function($classes, $item, $args) {
if (!isset($_GET[‘parent’]) || empty($_GET[‘parent’])) return $classes;
if ($item->object_id == $_GET[‘parent’]) {
$classes[] = “current_page_item”;
$classes[] = “current-menu-item”;
}
return $classes;
}, 10, 3);

Now here comes the case, where this doesn’t work: When the parent is inside a sub menu then the parent of that sub menu does not get marked as active and the sub menu remains closed. So I need to add current-page-ancestor current-menu-ancestor current-menu-parent current_page_parent current_page_ancestor to the parent menu item inside that filter function.

So what I thought is, I need a $item->has_child($_GET[‘parent’]) which does not exists obviously.

Do you guys have any ideas about this?

Read more here:: How to set the currently active page in the menu including parents

Leave a Reply

Your email address will not be published. Required fields are marked *