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 tags and attributes etc…

https://jakearchibald.github.io/svgomg/

There are loads of useful customisable settings on there to clean up your SVGs but I like to really strip them back. I remove <g> tags, widths, heights, classes and I also change any styles to inline formatting for all the SVG elements. This way, I can style SVGs using CSS alone without the need for the dreaded !important being used to override them.

Put this in your themes functions.php

// this location might need changing depending on the site/theme
define('SVG_LOCATION', get_bloginfo('template_url') . '/assets/svg/');

function get_svg($svg, $width = null, $height = null, $classes = null)
{

    if (!function_exists('curl_init')) {

        $svg_code = 'The cURL library is not installed.';

    } else {

        if (filter_var($svg, FILTER_VALIDATE_URL)) {
            $svg_url = $svg;
        } else {
            $svg_url = SVG_LOCATION . $svg;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $svg_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $svg_code = curl_exec($ch);
        curl_close($ch);

        if (!empty($width)) {
            $svg_code = str_replace('<svg', '<svg width="' . $width . '" ', $svg_code);
        }

        if (!empty($height)) {
            $svg_code = str_replace('<svg', '<svg height="' . $height . '" ', $svg_code);
        }

        if (!empty($classes)) {
            $svg_code = str_replace('<svg', '<svg class="' . $classes . '" ', $svg_code);
        }

    }

    return $svg_code;
}

Then when you need an SVG in your theme just call it in 2 ways…

If you want to display an SVG that’s located in your themes folders just add in the SVG file name (width, height and classes are optional):

echo get_svg('example.svg', 100, 200, 'example-class-here');

or if you have an SVG uploaded in WordPress media (or even an externally sourced one) you simply use the URL to the SVG:

// from the media library...
$some_svg = wp_get_attachment_url(12);
echo get_svg($some_svg);

// or external...
echo get_svg('https://example.com/example.svg');