Filtering Classes on wp_nav_menu

WordPress menus are awesome and pretty powerful, but sometimes they don’t do quite what you need.

Today we are going to look at adding a special CSS class to a single WordPress menu item. In our scenario we have a page called ‘Our Portfolio’ set in our menu. On it we use a couple shortcodes to show posts from our portfolio categories. The problem comes when we view a single portfolio item, the menu item ‘Our Portfolio’ is not highlighted to show it’s ancestry. Well lets fix that.

If you’re just up for a screencast, jump to the bottom.

Our Code

So let’s start by jumping in to our code.

/**
 * Filters the menu classes so that we can make a page appear to be the ancestor of
 * a single CPT view.
 *
 * @since 1.0
 * @author SFNdesign, Curtis McHale
 *
 * @param array     $classes    required        The existing classes
 * @param object    $item       required        The post object information for the menu item
 *
 * @return array    $classes    Our modified classes
 *
 * @uses get_post_type()        Gets the post type for given object or post_id
 */
function wptt_menu_classes( $classes, $item ){

	global $post;

	if ( get_post_type( $post ) == 'portfolio' && $item->title == 'Our Portfolio' ){
		$classes[] = 'current-page-ancestor';
	}

	return $classes;

} // menu_class
add_filter( 'nav_menu_css_class', 'wptt_menu_classes', 10, 2 );

Lets start by looking at our filter nav_menu_css_classes. This filter allows us to change the classes on the menu items. We set the priority to 10 and the 2 means that we are passing 2 items through the filter.

The 2 items we pass through the filter are $classes and $item. $classes is an array of the classes that are already on the menu item. $item is a post object that corresponds to the menu item. Since the filter doesn’t pass our overall $post object we have to declare it as a global.

Now we write a conditional using get_post_type() to check if we are on a ‘portfolio’ post type page and if our current menu item title matches ‘Our Portfolio’. When both of those conditions are met, we add the CSS class current-page-ancestor to our menu item.

We use current-page-ancestor because that is a stock WordPress CSS class and there is no point in getting fancy and writing our own. If WordPress has something, just use it.

Really that’s it. Now when we view a single portfolio entry the ‘Our Portfolio’ menu item will have the CSS class current-page-ancestor applied and we can use that to make sure it’s highlighted.

Screencast

Curtis McHale

Posts Twitter Google+

Curtis is a web designer/developer specialized in WordPress eCommerce development on WooCommerce. You can get in touch with him about projects on SFNdesign.
My Blog is 4 Times Faster Than Your Blog

Trackbacks and Pingbacks:

  1. Filtering Classes on wp_nav_menu : Post Status - May 14, 2013

    [...] Filtering Classes on wp_nav_menu » [...]