Categories
CMS Mastering Development Wordpress

How to add class to specific navbar item when post parent category is in specific category

I have website with pages which are named the same as categories. For example I have page called Cities and also I have category called Cities. I want to add class to navbar item when user is reading post from specific category. So when I’m reading post from category Cities I want to highlight link in my navbar which going to page Cities. I made simple function

add_filter('nav_menu_css_class' , 'my_nav_special_class' , 10 , 2);
  function my_nav_special_class($classes, $item){

    global $post;

    $category   = get_the_category();

    $slug = $category[0]->slug;
    $slug = str_replace('-', '', strtolower($slug));

    $menu_item = sanitize_title( $item->title );
    $menu_item = str_replace('-', '', strtolower($menu_item));

    if( is_single() && $slug === $menu_item) {
      $classes[] = 'current_page_item';
    }

   return $classes;
}

When the post category match navbar item I’m adding css class. The problem is when post category is for example Tiger and in navbar I have page called Animals. In this case I want to highlight navbar item too. My question is – how can I do this? How the condition should look like when I want to add css class to specific menu item when post have specific cat or cat parent?

Leave a Reply

Your email address will not be published. Required fields are marked *