Skip to content

Instantly share code, notes, and snippets.

@jrtashjian
Created December 7, 2018 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrtashjian/dd3ca4e2c0481d7f7c254351e765a8a6 to your computer and use it in GitHub Desktop.
Save jrtashjian/dd3ca4e2c0481d7f7c254351e765a8a6 to your computer and use it in GitHub Desktop.
<?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