Add FontAwesome to WordPress posts with a Shortcode

Every now and again we require a FontAwesome icon to be added as part of the WordPress post content, now FontAwesome are really good and give you the html code for each icon to copy into your post. All accessible via the icon list linked above. It is easy to drop the html tag into your code as long as the post edit box is set to ‘Text’ (rather than ‘Visual’), however that same process can cause confusion for less experienced users.

A good solution is to add the code below to your functions file. We are assuming you have already enqueued the FontAwesome library. It’s a simple function, and assumes you will add an attribute to the shortcode called “fa” which equals the icon you want to display..

add_shortcode('icon', function ($attr) {
	if(isset($attr['fa'])) {
		return '<i class="fa fa-' . $attr['fa'] . '" aria-hidden="true"></i>';
	}
});

The shortcode process adds the initial “fa-” part of the icon class, so you do not need to include that within the shortcode, just the name of the icon. This is the link to the list of FontAwesome icons. The shortcode also allows you to add extra classes to take full advantage of the FontAwesome functionality.

Shortcode examples:

[icon fa="envelope"]
[icon fa="angle-down"]
[icon fa="bath fa-2x fa-spin"]

One response to “Add FontAwesome to WordPress posts with a Shortcode

Leave a Reply

Your email address will not be published. Required fields are marked *