Skip to content

Instantly share code, notes, and snippets.

@brunomonteiro3
Last active August 29, 2015 14:24
Show Gist options
  • Save brunomonteiro3/a80c12432cf7fbb9e9d7 to your computer and use it in GitHub Desktop.
Save brunomonteiro3/a80c12432cf7fbb9e9d7 to your computer and use it in GitHub Desktop.
This code will add an class to each item on your theme menu - this way you can customize each item based on their slug rather than their ID (which can change when the database changes).
function add_slug_class_to_menu_item($output){
$ps = get_option('permalink_structure');
if(!empty($ps)){
$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.'">/', 'item-'.$slug.'">', $output, 1);
}
}
return $output;
}
add_filter('wp_nav_menu', 'add_slug_class_to_menu_item');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment