How to highlight 1st level menu item based on actual page

I am trying to highlight 1st level menu item by adding 'current-menu-item' class using nav_menu_css_class filter based on actual page / article / post / etc.

For example, menu looks like this:

Publications - Computers - Article 123

So, once user enters Article 123 page I would like to highlight Publications menu section. Is it possible?

Topic sub-menu child-pages pages menus Wordpress

Category Web


Yes, very much possible and you don't even have to add classes yourself. If you're using wp_nav_menu, Wordpress adds classes for every case the specific nav item is in. I'll name the important classes for Publications (amongst others), based on where you clicked hypothetically:

  1. Publications - This is now the selected item, and will get (amongst others) the classes: current-menu-item because it's selected

  2. Computers - Publications is not the selected item, but will get the classes: current-page-parent and current-menu-parent because it's direct child is the selected item, and current-page-ancestor and current-menu-ancestor because one of it's children down the line is the selected item

  3. Article 123 - Publications is not the selected item, but will get the classes: current-page-ancestor and current-menu-ancestor because one of it's children down the line is the selected item

So in short, current-menu-item when selected, [classname part]-parent when direct child is selected and [classname part]-ancestor when child, grand-child or deeper level child is selected

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.