Created
December 7, 2018 07:32
-
-
Save jrtashjian/dd3ca4e2c0481d7f7c254351e765a8a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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