Skip to content

Instantly share code, notes, and snippets.

@briankompanee
Last active July 15, 2016 18:39
Show Gist options
  • Save briankompanee/a44a2b9151ffd45dfd1a36c5b07b23be to your computer and use it in GitHub Desktop.
Save briankompanee/a44a2b9151ffd45dfd1a36c5b07b23be to your computer and use it in GitHub Desktop.
WordPress: Add the page or post slug as a class to a menu item.
<?php
/**
* Add the page or post slug as a class to a menu item.
* Add to functions.php
*/
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.'">/', 'menu-item-'.$mid.' menu-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