Using Inline SVG Sprites in WordPress Themes

I have been integrating inline SVGs into some of my latest WordPress themes. This is just a quick tutorial on the techniques that I have experimented with. Feel free to leave feedback and suggestions in the comments below – I’m all ears.

So let’s get it started!

Inline SVG simply refers to SVG markup that is included in the markup for a webpage. Using an inline SVG sprite will save an HTTP request but it does mean the sprite is not cached by the browser. Also, note that browser support is good to go these days.

Throughout this tutorial I will am using /images/sprite.svg.php as my sprite and directory location.

Include your SVG Sprite

First off, you will need to include your sprite directly following the opening body tag, to ensure maximum compatibility throughout your templates. I found the easiest method to retrieve the sprite is to use the native get_template_part() function, directly in the header.php file.

Here’s a screenshot:

Modify the SVG extension

Add the .php extension to your sprite image file, so that it becomes .svg.php. Essentially, sprite.svg is now sprite.svg.php. You could add a Gulp copy task to build a duplicate sprite.svg.php file for you, but for the purpose of this tutorial, we are just renaming the .svg file. That’s on my todo list for sure!

Use Inline SVGs

At this point, you should see your sprite loaded in your source code. Now you’re all set to include the SVG’s throughout your theme. Below is the method I’ve grown to use. I typically interchange the second div element with an <a> element if required.

Edit: I have updated the gist to check if the sprite is loaded via the Customizer. If so, we need to add get_template_directory_uri() in order to load the sprite appropriately in the Customizer view.

Add Styling

For styling, I include the .svg__wrapper styles once, and then assign height and width attributes to particular SVGs throughout the theme. I’ve found this to be the most efficient method so far to prevent doubling up on CSS – although if you have better alternative, I’d love to see it.


All in all, this is the method that I’ve been experimenting with lately. Again, I’d appreciate any feedback or suggestions – just leave a comment below.

Also published on Medium.

Start the Conversation

Leave a Reply

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