Highlighting Custom Post Types in the menu

There seems to be a problem/oversight in WordPress at the moment (afaik).

You can generate Custom Post Types (CTP) easily enough, and have them visible on any page using templates/the loop, but when you click through to a single CTP WordPress assigns the current_page_parent to the default posts page. For many that will mean highlighting the News or Blog pages of their site.
After a lot of searching, and finding lots of people asking the same question but no solutions (except hacks), I found a reply by jonny_williams to a post about this on the wordpress.org/support forum. His solution at least runs from functions.php (and so before the content is displayed) rather than being accomplished through javascript like many others.

After a couple of modifications I settled on this:

function fix_portfolio_parent($menu){
	global $post;
	if ( 'projects' == get_post_type() )
	{
		$menu = str_replace( 'current_page_parent', '', $menu ); // remove all current_page_parent classes
		$menu = str_replace( 'menu-item-XXX', 'current_page_parent menu-item-XXX', $menu ); // add the current_page_parent class to the page you want
	}
	return $menu;
}
add_filter( 'nav_menu_css_class', 'fix_portfolio_parent', 0 );

Just replace the XXX with the number of the parent page you want to highlight, and 'projects' with the name of your CTP. As always, make sure you function name is unique and relevant. If you have multiple CTPs, either duplicate this for each, or extend the if (I haven’t looked at the performance differences of these options).

Category:

Tags:

One response to “Highlighting Custom Post Types in the menu”

  1. Huw Rowlands avatar

    This snippet is just what I needed! Thanks so much!!

Leave a Reply

Your email address will not be published. Required fields are marked *