I'm using a WordPress Menu to create a navigation structured like this:
- Home
- About
- Contact
- Sub Page
Using this code from kuroi's response here I'm able to add first-menu-item
and last-menu-item
classes to the list items above:
function add_first_and_last($output) {
$output = preg_replace('/class="menu-item/', 'class="first-menu-item menu-item', $output, 1);
$output = substr_replace($output, 'class="last-menu-item menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item'));
return $output;
}
add_filter('wp_nav_menu', 'add_first_and_last');
However the last-menu-item
class is being added to the Sub Page list item (because it's the last) rather than to the Contact list item.
Question: How can I make this function apply only to the top level items of a menu?
Thanks!