Archived topic
Span class around menu item titles?
3 replies · Started by John on October 5, 2022
Is it possible to put a span class around menu item titles? As in: #site-navigation .inside-navigation ul.menu li a span (?)
I'm just wondering if there's a filter for this or some piece of code that can modify the GP menu walker to add the span around the titles.
Thanks,
John
Hi John,
WordPress has this filter - wp_nav_menu_items: https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/
You can use this filter to alter the menu. So for instance, one very simple way to do it is through something like this:
add_filter( 'wp_nav_menu_items', 'prefix_add_div', 15, 2 );
function prefix_add_div( $items, $args ) {
if( $args->theme_location != 'primary' ) {
return $items;
}
$myreplace1 = '</a>';
$myinsert1 = '<span>MY span</span></a>';
$items = str_replace( $myreplace1, $myinsert1 , $items );
return $items;
}
Hi Fernando,
Thanks for your help. That solution is close but wasn't quite what I was looking for. You helped me figure it out, however.
Here is the code that accomplished what I wanted:
add_filter( 'walker_nav_menu_start_el', 'gpc_span_to_nav_menu', 10, 4 );
function gpc_span_to_nav_menu( $item_output, $item, $depth, $args ) {
$item_output = 'url .'" title="'. $item->attr_title .'"><span class="menu-title">'.$item->post_title.'</span >';
return $item_output;
}
Glad you got it working and thank you for sharing!