How to Highlight the Current Page in WordPress Menu

Home » Snippets » How to Highlight the Current Page in WordPress Menu
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

One of the key elements of any website is the navigation menu. It helps visitors easily navigate through different pages and sections of the site. As a website owner or developer, you may be looking for ways to improve the user experience and make it more intuitive for your visitors to know which section they are currently on. One effective way to achieve this is by highlighting the current page in the menu. In this article, we’ll discuss different methods and techniques to implement this feature on your WordPress website.

					function wpturbo_highlight_current_menu_item($classes, $item) {
    if (in_array('current-menu-item', $classes)) {
        $classes[] = 'active';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'wpturbo_highlight_current_menu_item', 10, 2);
				

The code snippet provided is used to highlight the current page in the menu. This is particularly useful when you want to provide visual feedback to users, allowing them to easily identify which page they are currently on.

The code snippet defines a function called wpturbo_highlight_current_menu_item which takes two parameters: $classes and $item. The $classes parameter is an array of CSS classes that are assigned to the menu item, and the $item parameter represents the current menu item.

Inside the function, we check if the array of classes contains the class current-menu-item. This class is automatically added by WordPress to the menu item that corresponds to the current page. If the class is present, we add an additional class called active to the array of classes.

if (in_array('current-menu-item', $classes)) {
    $classes[] = 'active';
}

By adding the active class, we can apply custom styling to the current menu item to visually distinguish it from the other menu items.

Finally, the function returns the modified array of classes. This allows other functions or filters to further manipulate the classes if needed.

The last step is to hook the wpturbo_highlight_current_menu_item function into the nav_menu_css_class filter. This filter is called whenever WordPress generates the CSS classes for a menu item. By hooking into this filter, we can modify the classes and add the active class to highlight the current menu item.

add_filter('nav_menu_css_class', 'wpturbo_highlight_current_menu_item', 10, 2);

This code ensures that the wpturbo_highlight_current_menu_item function is executed whenever the nav_menu_css_class filter is applied during the menu rendering process. As a result, the current menu item will have the active class added to it, allowing for custom styling to be applied.

Register an account to save your snippets or go Pro to get more features.