Skip to content

Instantly share code, notes, and snippets.

@ajithrn
Last active August 29, 2015 14:06
Show Gist options
  • Save ajithrn/1f059b2201d66f647b69 to your computer and use it in GitHub Desktop.
Save ajithrn/1f059b2201d66f647b69 to your computer and use it in GitHub Desktop.
Wordpress: CPT active menu class fix
<?php
/**
* cusom post type active menu item fix
* not 100% working, it does remove the class,
* but if you are using custom page template to display post type, the active class insertion might not work
*
* @autor : ajith
* @url : http://trytoinnovate.com
* @referance : https://gist.github.com/AlphaBlossom/ae2f676d4763d1f1b3a2
*
*/
add_filter( 'nav_menu_css_class', 'cpt_active_class_fix', 10, 3 );
function cpt_active_class_fix( $classes, $item, $args ) {
global $post;
$current_post_type = get_post_type_object(get_post_type($post->ID)); //getting current post type
$current_post_type_slug = $current_post_type->rewrite[slug]; //getting current page slug
$menu_slug = strtolower(trim($item->url)); // Getting the URL of the menu item
//check if its custom post type and not a regular post
if( ( $current_post_type != 'post' ) && ( is_home() || is_single() || is_archive() || is_category() || is_tag() || is_author() ) ) {
//getting home/blog page id
$blog_page_id = intval( get_option('page_for_posts') );
if( $blog_page_id != 0 && $item->object_id == $blog_page_id ) {
//remove the active class
unset( $classes[array_search( 'active', $classes )] );
}
}
// 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 $classes;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment