Mark parent category menu active on single custom post view in WordPress

Recently I developed a theme for one of my clients and I had to highlight the menu item of the parent category in the main menu when one of its associated single custom posts was viewed. For that, I had to add an action in my functions.php file for nav_menu_css_class. It returns the ‘active’ class, which WordPress adds to the parent category menu item in the main menu. You can see the code at Gist here or below.

<?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;
}
?>

Adding above code in you functions.php file will do the trick.

Click here to read more on WordPress.

Share your love
Muhammad Jawaid Shamshad
Muhammad Jawaid Shamshad
Articles: 128

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.