0

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?

0

It seems like you should use hierarchies of categories, because it sounds like 'Tiger' belongs to the group 'Animals'.

You can get the parent category with $category->parent so if page category was Tiger, and parent category was Animals, this would then work.

Let me know if that would work for you and if you need more info

| improve this answer | |
  • Yes and no. Let me explain it little bit more specific. Situation first, when my code works. I have page with slug for example "cars" which have query that list posts from category "Cars" This category also have slug "cars". So when I'm in post from category "cars" my menu item called "Cars" will have extra class. Situation two, when this code don't work. I have page with slug "companies-news". This page have query which shows posts from categoriy "company". In this case these both slugs are different so my code didn't work. But yeah, I think I just change parent cat slug and it should work – MMPL1 Jun 30 at 18:05
  • Well you can't just change the parent cat, I'm proposing you change the parent category but then also add a second condition in your code that checks the parent category as well. So a post in category Tiger would match a menu item called Tiger or Animals – mozboz Jun 30 at 18:07
  • I just change category slug and add condition to check if post have parent category. So now it's working. Thanks! – MMPL1 Jul 1 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.