WordPress Snippets

How to add a custom class to the current 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 );
}

Leave a Reply