mcgwier
4/1/2015 - 3:00 PM

Add page/post slug class to menu item classes

Add page/post slug class to menu item classes

<?php

add_filter( 'wp_nav_menu_objects', 'cam_add_menu_slug_class' );
function cam_add_menu_slug_class( $items ) {
	
	// Add parent class
	$parents = array();
	foreach ( $items as $item ) {
		if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {
			$parents[] = $item->menu_item_parent;
		}
	}
	
	foreach ( $items as $item ) {
		if ( in_array( $item->ID, $parents ) ) {
			$item->classes[] = 'menu-item-parent'; 
		}
	}

	// Add slug class
	foreach ($items as $key => $item) {
		$items[$key]->classes[] = 'menu-' . sanitize_title($item->title);
	}
	
	return $items;
}