Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Add the 'current-menu-ancestor' class to a parent page menu item where the child page is not part of the menu.
*
* @param array $classes The CSS classes that are applied to the menu item's <li> element
* @param WP_Post $item The current menu item
*
* @return array The filtered CSS classes.
*/
function active_parent_in_menu_for_page( $classes, $item )
{
global $post;
if ( !is_page() ) {
return $classes;
}
$page_parents = get_post_ancestors( $post );
$topmost_parent = array_pop( $page_parents );
if ( empty( $topmost_parent ) ) {
return $classes;
}
if ( $topmost_parent == $item->object_id ) {
array_push( $classes, 'current-menu-ancestor' );
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'active_parent_in_menu_for_page', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment