Skip to content

Instantly share code, notes, and snippets.

@alandbh
Last active September 17, 2017 03:33
Show Gist options
  • Save alandbh/73e17aa899d23a8c6601dbbd24bb0111 to your computer and use it in GitHub Desktop.
Save alandbh/73e17aa899d23a8c6601dbbd24bb0111 to your computer and use it in GitHub Desktop.
This code sets de current menu item for single CPT
/* ----------------
It applies the class "active" or "current-menu-item" on menu item of a parent page
Alan
----------------- */
add_action('nav_menu_css_class', 'add_current_nav_class', 10, 2 );
function add_current_nav_class($classes, $item) {
// Getting the current post details
global $post;
// Getting the post type of the current post
$current_post_type = get_post_type_object(get_post_type($post->ID));
$current_post_type_slug = $current_post_type->rewrite[slug];
// Getting the URL of the menu item
$menu_slug = strtolower(trim($item->url));
// If the menu item URL contains the current post types slug add the current-menu-item class
if (strpos($menu_slug,$current_post_type_slug) !== false) {
$classes[] = 'current-menu-item';
}
// Return the corrected set of classes to be added to the menu item
return $classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment