WordPress lets you add descriptions on menu items by clicking “Screen Options” when editing the menu (top right corner) and checking “Description”. But most themes don’t support these out of the box, so you’ll need to add support yourself.
Most approaches I’ve seen call for using walkers, which are complicated and could conflict with your theme if you’re already using a custom walker. This solution is much simpler.
In the code below I’m using the 'walker_nav_menu_start_el'
filter to modify the menu item. I’m checking to see if the menu is in the ‘header’ theme location (I only wanted this on one specific menu), that $depth = 0 (it’s a top level menu item), and that the menu item has a description. If all of those are true, I add the description to the end of the menu item.
Another benefit to this approach is it can be used in conjunction with other menu customizations, like adding arrows to menu items.
<?php | |
/** | |
* Descriptions on Header Menu | |
* @author Bill Erickson | |
* @link http://www.billerickson.net/code/add-description-to-wordpress-menu-items/ | |
* | |
* @param string $item_output, HTML outputp for the menu item | |
* @param object $item, menu item object | |
* @param int $depth, depth in menu structure | |
* @param object $args, arguments passed to wp_nav_menu() | |
* @return string $item_output | |
*/ | |
function be_header_menu_desc( $item_output, $item, $depth, $args ) { | |
if( 'header' == $args->theme_location && ! $depth && $item->description ) | |
$item_output = str_replace( '</a>', '<span class="description">' . $item->description . '</span></a>', $item_output ); | |
return $item_output; | |
} | |
add_filter( 'walker_nav_menu_start_el', 'be_header_menu_desc', 10, 4 ); |