Display menu descriptions with HTML in WordPress

One of these days I’ll get around to finishing the Wedding recap post I started….ehh months ago. Today is not that day. 

So we are updating our navigation look and feel on our WordPress website. With that new look, it involved displaying menu descriptions with HTML. By default, it’s easy to add the description field. Displaying in the theme was a little harder. Even harder was displaying HTML. With a couple of adjustments in the theme’s functions.php file, it’s possible. 

/**
 * Enable the ability to have HTML in menu desc.
 */
remove_filter( 'nav_menu_description', 'strip_tags' );
function my_plugin_wp_setup_nav_menu_item( $menu_item ) {
    if ( isset( $menu_item->post_type ) ) {
        if ( 'nav_menu_item' == $menu_item->post_type ) {
            $menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content );
        }
    }

    return $menu_item;
}
add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' );

/**
 * Enables the display of menu descriptions.
 */
function prefix_nav_description( $item_output, $item, $depth, $args ) {
    if ( !empty( $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', 'prefix_nav_description', 10, 4 );

The first method makes it where the menu description field doesn’t strip HTML tags when you save the menu. The second method makes it where the description is easier to target style wise. In my case, I needed to use it with some fancy jQuery to switch in and out the descriptions. 

Shout out to StackOverflow for nearly always having some sort of answer to everything code related.

Happy coding!