In WordPress there’s an option to add custom descriptions to Menu links – but by default there’s no way to display these descriptions. I’m currently redesigning Binary Moon and wanted to add descriptions to the menu – so I thought I’d work out how to do it.
Googling around it seemed that I would have to create a custom walker class and do all sorts of complicated stuff – but then I realised the current default theme, Twenty Fifteen, has menu descriptions – and their solution is super simple.
It’s just a filter on the returned link menu items using a str_replace to inject the description.
/**
* Add descriptions to menu items
*/
function bm_nav_description( $item_output, $item, $depth, $args ) {
if ( 'primary' == $args->theme_location && $item->description ) {
$item_output = str_replace( $args->link_after . '</a>', '<div class="menu-item-description">' . $item->description . '</div>' . $args->link_after . '</a>', $item_output );
}
return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'bm_nav_description', 10, 4 );
Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).
Link to this page
Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.