I am creating custom WordPress theme using a starter theme _Underscores and Bootstrap.
I would like to modify wp_nav_menu
so that it assigns the current menu item .active
class instead of the default .current-menu-item
. I need this in order to use .active
class from Bootstrap.
Here is what I have (extra stuff comes from WP so please scroll to the right):
<ul id="menu-main-menu" class="nav navbar-nav">
<li id="menu-item-14" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-13 current_page_item menu-item-14"><a href="">item1</a></li>
<li id="menu-item-12" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12"><a href="">item2</a></li>
</ul>
And here is what I need:
<ul id="menu-main-menu" class="nav navbar-nav">
<li id="menu-item-14" class="active menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-13 current_page_item menu-item-14"><a href="">item1</a></li>
<li id="menu-item-12" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12"><a href="">item2</a></li>
</ul>
I would prefer to achieve this without modifying ../wp-includes/nav-menu-template.php
and without using JS.
UPDATE: I found the answer just before posting this question, but since I had a rather hard time finding it, posting this as a QA to hopefully save someone some time.
Just paste this code into functions.php file:
More on wordpress.org:
.active
class to active menu itemTo also highlight the menu item when one of the child pages is active, also check for the other class (
current-page-ancestor
) like below:If you want the ‘active’ in the html:
header with html and php:
functions.php:
In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for
current-post-ancestor
:In
header.php
insert this code to show menu:In
functions.php
use this: