I have not written anything for a long while, and before I had not written much as I am not really a blogger and I only write something when I actually have something that I want to share, which I do today.

Once in a while you have to create a menu that has different colors for each menu item. Now since the introduction of the menu builder in wordpress 3.0 or with one of the menu builder plugins like WP menubar, you can add a class to each item. This though gets a bit tedious if you work on a local version of the site first and then have to update everything on a production version later.

Personally I think that the page/post slug should be part of the menu item classes instead of the menu item id number which less intuitive to use as classes in your style sheet, but it is probably a matter of taste.

Anyway, here is a filter that you can put in your functions.php to automatically add menu-item-slug, where slug in the page/post slug to the menu item classes, when you use the new WordPress menu system, wp_nav_menu. It also checks to see if you have a permalink structure and if it is not present, it will not add anything to your menu item classes.

function add_slug_class_to_menu_item($output){
	$ps = get_option('permalink_structure');
		$idstr = preg_match_all('/<li id="menu-item-(\d+)/', $output, $matches);
		foreach($matches[1] as $mid){
			$id = get_post_meta($mid, '_menu_item_object_id', true);
			$slug = basename(get_permalink($id));
			$output = preg_replace('/menu-item-'.$mid.'">/', 'menu-item-'.$mid.' menu-item-'.$slug.'">', $output, 1);
	return $output;
add_filter('wp_nav_menu', 'add_slug_class_to_menu_item');

Thanks to Josh Stauffer for a great simple way to get the page/post slug.
Also thanks to these guys on the WP forums for explaining how to add filters to the menu items. By the way, this is also a great resource if you want to add first/last classes to your menu items.