I like to remotely host my SVGs and then call them in my code. For the most part, this works well, and I wrote out some basic code to check if they’re defined and accessible before displaying.

But what if you wanted your fallback to be a font-icon?

And remember, you want your code to be DRY as a bone. So no repeating chunks of code all over the place, please and thank you.

The Code

There is but ONE requirement here. You have to define HALFELF_SYMBOLICONS_PATH as the path to your SVGs. In my case, mine is something like http://my-cool-icons.objects-us-west-1.dream.io/svgs/ because I’m using DreamObjects for them. Any cloud host works great for this, mind you.

function halfelf_symbols( $svg = 'square.svg', $fontawesome = 'fa-square' ) {	

	$icon = '<i class="fa ' . $fontawesome . '" aria-hidden="true"></i>';

	if ( defined( 'HALFELF_SYMBOLICONS_PATH' ) ) {
		$response      = wp_remote_get( HALFELF_SYMBOLICONS_PATH );
		$response_code = wp_remote_retrieve_response_code( $response );
		if ( $response_code == '200' ) {
			$get_svg      = wp_remote_get( LP_SYMBOLICONS_PATH . $svg );
			$response_svg = wp_remote_retrieve_response_code( $get_svg );
			$icon         = ( $response_svg == '200' )? $get_svg['body'] : 'square.svg';

	return $icon;

This checks for the existence of the server used and if the actual icon exists before it sets things.

Usage Example

In my code, I define it like this:

$icon  = halfelf_symbols( 'users.svg', 'fa-users' );
$title = '<span role="img" aria-label="users" title="Users" class="TEMPLATE users">' . $icon . '</span>';

This sets the icon and then calls the span which will help make this more accessibility friendly. I could have coded the span into the function, but since I often have it all dynamically generated, it worked more sustainably this way.

In this example, I call it like this:

the_archive_title( '<h1 class="page-title">' . $title . '</h1>' );

And voila. Icons in my page title.

Reader Interactions

%d bloggers like this: