Add Font Awesome To WordPress Menu Items

Font awesome is a huge library of icons that uses fonts and CSS pseudo selectors to add these icons to your page. This technique means loading the icons is very fast and you have full control over the colour and size of the icons simply by using CSS. In this tutorial we're going to look at how you can add these icons to your WordPress menu based on the menu item details. To start with we need to add font awesome onto our theme, to do this we can either download Font Awesome here, or you can use the embed code to include Font Awesome from a CDN.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />

To use these icons we need to add a CSS class to an element, for example if I wanted to add a hamburger menu icon to the page we will use the CSS class fa fa-bars.

<i class="fa fa-bars" aria-hidden="true"></i>

To add these to your WordPress menu you need to use the filter nav_menu_link_attributes this is used to change the attributes added to your HTML code on each link of your menu. With this filter you'll have access to 3 properties in the function

  • $atts - The existing HTML attributes
  • $item - Object containing the item details
  • $args - Array containing config with desired markup of nav item

We will need to edit the $atts['class'] element to add the CSS class to your menu item. We can do this by the title of the menu item, for example if the menu item is for a contact page you can add an envelope icon next to the menu item.

function pu_add_contact_icon( $atts, $item, $args )
{
    if(strtolower($item->title) == 'contact')
    {
        $atts['class'] = 'fa fa-envelope';
    }

    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'pu_add_contact_icon', 10, 3 );

If this menu item has a title that is likely to change over time then you could use another property to select the correct item like the $item->ID. For more icons to select from visit the Font Awesome Icons page. Font Awesome Icons

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring