Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mjawaids/d9f95795f1cdc71df79e0db1ba6444ae to your computer and use it in GitHub Desktop.
Save mjawaids/d9f95795f1cdc71df79e0db1ba6444ae to your computer and use it in GitHub Desktop.
Mark (highlight) custom post type parent as active item in Wordpress Navigation.When you visit a custom post type's single page, the parent menu item (the post type archive) isn't marked as active. This code solves it by comparing the slug of the current post type with the navigation items, and adds a class accordingly.
<?php
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[] = 'active';
}
// Return the corrected set of classes to be added to the menu item
return $classes;
}
?>
@mjawaids
Copy link
Author

Updated to fix a bug where $current_post_type->rewrite['slug']; was missing quotes in 'slug'. And returned class 'active' for Bootstrap/Underscore based themes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment