Skip to content

Instantly share code, notes, and snippets.

@AndreFCAmorim
Created November 10, 2022 10:47
Show Gist options
  • Save AndreFCAmorim/011274d980fda27bb094ac1ff87e7aea to your computer and use it in GitHub Desktop.
Save AndreFCAmorim/011274d980fda27bb094ac1ff87e7aea to your computer and use it in GitHub Desktop.
Add a custom class to the active menu item
<?php
add_filter( 'nav_menu_css_class', 'add_class_to_active_menu_item', 10, 2 );
/**
* Method add_class_to_active_menu_item
*
* This method adds an extra class to the menu item when it's active.
* Should be called in the hook 'nav_menu_css_class'.
*
* https://developer.wordpress.org/reference/hooks/nav_menu_css_class/
*
* @param array $classes Array of the CSS classes that are applied to the menu item's <li> element.
* @param WP_POST $item The current menu item object.
*
* @return array Contains classes
*/
function add_class_to_active_menu_item( $classes, $item ) {
$full_request_url = '';
if ( ( !empty($_SERVER['HTTPS'] ) ) && ( $_SERVER['HTTPS'] !== 'off' ) ) {
$full_request_url .= 'https://';
} else {
$full_request_url .= 'http://';
}
$full_request_url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ( $item->post_type == 'nav_menu_item' && $item->url == $full_request_url ) {
$classes[] = 'current-menu-item';
} else {
return $classes;
}
return array_unique( $classes );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment