Tips & Tricks

How to Make Menu Item is Active in Different Situations

How to Make Menu Item is Active in Different Situations

One of my buyers wrote me question in support of my theme. “How make the menu item Blog active when the single post page is open”. And I decided to make a post on this topic and describe a few situations how we can do it.

The first situation, let’s make the menu item Blog active

We can take the menu item’s title or it’s ID to construct the condition, I will use both.

// Activated menu item
add_filter('wp_nav_menu_objects', function( $menu_item )
{
	global $post;
	
	foreach ($menu_item as $item)
	{
		if( is_single() && $post->post_type == 'post' )
		{
			if( $item->title == 'Blog' && $item->ID == 44 )
				$item->classes[] = 'current-menu-item';
		}
	}

	return $menu_item;
}, 10, 2);
Where can we see the ID of the menu item

The second situation, how to make the menu item of the parent page active

Imagine that we have several pages, one of them is parent and all the other children. We want to add a parent page in the top menu and for the children pages we make the new menu and put it in the sidebar. In this case, when one of the child pages is active, we need the parent page in the top menu to be active too.

// Activated menu item
add_filter('wp_nav_menu_objects', function( $menu_item )
{
	foreach ($menu_item as $item)
	{
		if( is_page() ) 
		{
			global $post;
			
			if( isset( $post->post_parent ) 
			    && $post->post_parent 
			    && $item->object == 'page' 
			    && $item->object_id == $post->post_parent 
			    && !in_array( 'current-menu-item', $item->classes ) 
			) 
				$item->classes[] = 'current-menu-item';
		}
	}

	return $menu_item;
}, 10, 2);

I hope my examples will be useful to you, and you will be able to apply them in your projects.

Leave a comment

Subscribe to our Newsletter

Something BIG is coming, you'll be the first to know about it.