Skip to content

Instantly share code, notes, and snippets.

@diggeddy
Last active January 17, 2023 10:13
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 diggeddy/dcfb6a55c9537eb1c233b7b1069b9af2 to your computer and use it in GitHub Desktop.
Save diggeddy/dcfb6a55c9537eb1c233b7b1069b9af2 to your computer and use it in GitHub Desktop.
set current parent menui item
<?php
add_filter( 'wp_nav_menu_objects', 'add_menu_ancestor_parent_class' );
function add_menu_ancestor_parent_class( $items ) {
// ancestor classes to find
$ancestor = array('current-page-ancestor', 'current-post-ancestor');
$parents = array();
foreach ( $items as $item ) {
if ( array_intersect( $ancestor , $item->classes) ) {
$parents[] = $item->menu_item_parent;
}
}
// add class to ancestor parent menu item
foreach ( $items as $item ) {
if ( in_array( $item->ID, $parents ) ) {
$item->classes[] = 'current-menu-ancestor';
}
}
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment