How to add an icon to the parent menu in WordPress navigation

Sometimes we need to add a small icon to indicate that there is a submenu. While I could do this with JavaScript/jQuery, I usually like to find a way to implement the code directly, this way we don’t have to wait for JavaScript to load. While there are multiple ways, I often use those two approaches.

Add the image or the element directly into the menu.

Inside WordPress, when you create a menu, in the menu name you can directly add your image element or your element of choice if you use something like Font Awesome. In this example, I used an image, but you could use a span element and style it with CSS.

parent-li-has-image

Add the image or the element via a WordPress Filters.

WordPress offers filters hooks to modify or alter the functionality of various types of data. Using a filter, you can directly add your image or tag to the element that has children. You can insert the following filter in functions.php to add a span element inside the link.

/*
*
* Walker for the main menu 
*
*/
add_filter( 'walker_nav_menu_start_el', 'add_arrow',10,4);
function add_arrow( $output, $item, $depth, $args ){

//Only add class to 'top level' items on the 'primary' menu.
if('primary' == $args->theme_location && $depth === 0 ){
    if (in_array("menu-item-has-children", $item->classes)) {
        $output .='<span class="sub-menu-toggle"></span>';
    }
}
    return $output;
}

You can learn more about WordPress filters in WordPress Codex.

Bonus: Using a plugin

If you don’t know how to code or you want a fast solution,you can use Menu Icons plugin to add your favorite icon to the menu. WP Tavern has an excellent article “How to Easily Add Icons to Menus in WordPress” explaining how to use the plugin.