How to add "active" class to wp_nav_menu() current menu item (simple way)
🎉 How to Add the "active" Class to wp_nav_menu()
Current Menu Item (Simple Way) 🎉
Are you building a custom WordPress theme using the _Underscores and Bootstrap starter theme? Do you want to modify wp_nav_menu
so that it assigns the active
class to the current menu item, instead of the default current-menu-item
class? Well, you've come to the right place! In this guide, I'll show you a simple way to achieve this without modifying any core files or using JavaScript.
The Problem: Using the Bootstrap "active" Class for the Current Menu Item
By default, WordPress assigns the current-menu-item
class to the current menu item when generating the navigation menu using wp_nav_menu()
. However, you want to use the active
class provided by Bootstrap instead.
Here's an example of the HTML output by wp_nav_menu()
before adding the active
class:
<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's what you're aiming for:
<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>
The Solution: Using the nav_menu_css_class
Filter Hook
To add the active
class to the current menu item, we can leverage the powerful nav_menu_css_class
filter hook provided by WordPress. This hook allows us to modify the CSS classes applied to each menu item.
Open your
functions.php
file in your theme directory.Add the following code inside the file:
function add_active_class_to_menu_item($classes, $item) {
if (in_array('current-menu-item', $classes)) {
$classes[] = 'active';
}
return $classes;
}
add_filter('nav_menu_css_class', 'add_active_class_to_menu_item', 10, 2);
Save the file.
That's it! Now, when you generate your navigation menu using wp_nav_menu()
, the active
class will be automatically added to the current menu item, as desired.
Congratulations! 🎉
You have successfully added the active
class to the current menu item without modifying any core files or using JavaScript. Now you can style your current menu item using the Bootstrap active
class and achieve the desired visual effect.
Share Your Experience!
Did this guide help you solve the problem? Share your experience in the comments below! If you have any other questions or need further assistance, don't hesitate to ask.
Happy coding! ✨👩💻✨