Skip to content

Instantly share code, notes, and snippets.

@corypina
Created March 5, 2021 06:18
Show Gist options
  • Save corypina/d44b963e8d60903b3cd895513ae94b1c to your computer and use it in GitHub Desktop.
Save corypina/d44b963e8d60903b3cd895513ae94b1c to your computer and use it in GitHub Desktop.
Add "current" class to post type archive menu items when viewing single
<?php
/*
Give the "current-menu-item" class to archive links
in the menu when viewing singles of the post type.
1. Add the post type archive page to the menu (NOT as a custom link)
2. Add this filter.
*/
add_filter( 'nav_menu_css_class', function( $classes, $item ) {
$type = get_post_type();
$class_string = substr($item->classes[3], 17);
if ( $type == $class_string ) {
$classes[] = 'current-menu-item';
}
return $classes;
}, 10, 2 );
/*
This may not work if other custom menu classes are in play. The filter is looking
for the array of classes is the menu $item object.
It seems to always be in position [3], e.g.:
'menu-item-object-[post-type]'
The filter pulls the [post-type] from the class and compares it
to the post type currently being viewed.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment