Using SVG in custom WordPress themes

One of the few bugbears I have with WordPress is its lack of support for SVG file formats – I’m sure there are many plugins to be able to use SVGs in WordPress themes but I detest having to install a plugin when just few lines of code will do.

Firstly I’d like to share this life saving link that cleans up your SVG code from all those redundant <g> tags etc…

There is loads of useful customisable settings on there 👍

When I build a WP theme its normally bespoke to a design and to the client and so there are normally some core assets kept in the theme folder.

Put this in your themes functions.php

function get_svg($svg_file_name) {

   $path = __DIR__.'/assets/svg/'.$svg_file_name; // edit this to suit where you keep your SVGS in your theme folder
   $svg = file_get_contents($path);
   return $svg;

Then when you need an SVG in your theme just call it like this:

echo get_svg('example.svg');

Back to blog

Leave a Reply

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