LearnThe Perfect WordPress Inline SVG Workflow

   
Avatar

Galen Gidman
writes on January 23, 2014

Today we’re going to be looking at the perfect inline SVG workflow for WordPress. Before we go any further though, if you’re unfamiliar with the different varieties of SVGs, I highly recommend you take a quick read through Chris Coyier’s fantastic CSS-Tricks article on the subject.

Setting the Scene

Recently, I was working on a client project when I discovered the need to change the color of the logo based the state of the site header. Of course, I could just create two separate SVGs, each with a different fill color and simply change out the background image of my a.logo tag depending upon the state of the header, but that’s not necessary. With SVGs, all I have to do is embed the logo as an inline SVG and simply make the color change with the CSS fill property.

The only real problem with inline SVGs in my book is their sheer size. The particular logo I was working with was fairly complex as far as logos go and copying the SVG code right into my template would be pretty messy and take up a lot screen space. In his article, Chris makes mention of using the PHP include() function to embed SVGs, but if you’re working in WordPress there’s a better way to do it.

Enter get_template_part()

Instead, what we can use is WordPress’s native get_template_part() function. According to the WordPress codex, the purpose of get_template_part() is to:

Load a template part into a template (other than header, sidebar, footer) making it easy for a theme to reuse sections of code and an easy way for child themes to replace sections of their parent theme.

That’s nice and all, but we’re going to use it for something a bit different today. And they thought they could control us…

First, let’s drop the desired SVG into an images folder just inside the root of our theme. Now, rename the SVG to inline-[filename].svg.php. So, if its original name was logo.svg, name it inline-logo.svg.php.

Now it’s time for some get_template_part() action. get_template_part() accepts two parameters, the slug, and the name. Simply put, the slug is everything before the first hyphen (-) in the filename and the name is everything after.

So, to include our SVG, we’ll simply call get_template_part() and fill out the parameters like so:

get_template_part(‘images/inline’, ‘logo.svg’);

See how easy that was? Now, we’ve got clean code in our template file, an inline SVG embedded right into our page that can be styled with CSS, all with zero HTTP requests!

This is a method I’ve been relying recently and I’ve found to work really well, but I’d love to hear any and all suggestions. Fire off in the comments!

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

26 Responses to “The Perfect WordPress Inline SVG Workflow”

  1. Howard Lucas on April 28, 2018 at 1:49 pm said:

    Couldn’t get it to work until I changed the logo.svg to logo.php and imported the normal way

  2. This was spot on! Thanks!

  3. Hey,

    Sorry for the noob question, but I am not sure after I copy the code into my page template, how do I use the icon within an html page?

  4. Dean Wilson on December 12, 2017 at 7:31 pm said:

    IMO best to not change a file extension to php if you don’t actually want to change the type of file. Its an SVG and you want to use it as an SVG. Especially not viable if you are using a task runner (feels really bad to add an extension onto your SVGs or have two different versions, one for inlining and one for img tags and stylesheets… Instead, there is a good function that you can add to functions.php to do more intelligent includes. It will also allow you to pass data to your included file.

    Function here: http://codegists.com/snippet/php/hm_get_template_partphp_apsolut_php

    Then you can just do:

  5. very helpful article! many thanks for sharing the knowledge 🙂

  6. Demetrios on April 16, 2017 at 10:10 am said:

    Hello,

    I tried your method but I get:

    Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in filename.php on line: nnn
    ..
    Warning: include(): Failed opening ‘http://www.forakinderworld.com/yourdiet/wp-content/jimbo/mygraph.svg’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in filename.php on line nnn

  7. that worked perfect for me. thanks. fast and easy!

  8. Murray Chapman on May 9, 2016 at 10:29 pm said:

    I recently had to clean up a site that had a heap of php files injected and scattered throughout the file system. Some of them were in the images and js folder. A method of working with this was to stop the execution of PHP in these folders through a .htaccess inclusion. If that was included, would this stop your use of get_template_part()? I know you could just put the files somewhere else but I really like your creative approach.
    Thanks for the tut.

  9. This looks like it may be getting close to what I’m looking for, except that I need the image to be dynamic – in other words, client can choose an image in the ACF Options page, and then that SVG image needs to be added inline somehow so style changes can be applied as well. How might that be accomplished?

    • This method isn’t quite what you’re looking for. Off the top of my head:

      1. Install https://wordpress.org/plugins/svg-support/ to enable SVG uploads.
      2. Create ACF Image field that returned the image URL.
      3. Use this to output SVG file contents on the page: <?php echo file_get_contents( get_field( 'image_field', 'options' ) ); ?>

    • Another method that would be easy enough if it isn’t required for the user to be able to upload an SVG themselves (say if they’re just selecting from a predefined list):

      1) Create an ACF field with a “Select” list and define your selections.
      2) In your template, just use an if/elseif chain or, probably better, a switch statement to say “If the variable is this, show this SVG”. <– using this article to do it!

      Advantages are more control for you with the predefined list and you don't have to install a plugin. The disadvantage is that you have to add code with every new SVG design which isn't a big issue if it's not likely to change.

      Depends on your scenario though! Just thought I'd share this with others that run across this article!

      • Even better:

        1. Create a folder of available SVGs in the theme folder.
        2. Dynamically populate your select field (with the “Stylized UI” for searching capabilities) with the folder contents.
        3. Link to the SVG like:
        • Hi Galen, I’m using your suggestion of dynamically populating my select field with the contents of a folder of available SVGs. The select field is showing the labels correctly, but I can only get get_field(‘svg_select’) to return the value (e.g. 2), and not the label (e.g. ‘book-icon’). When I do a var_dump() both the value and label are set to 2… any idea why this is happening?

  10. can you please explain exactly what you do with:

    echo file_get_contents( get_template_directory_uri() . ‘/images/inline-header.svg’ );

  11. Beautiful and clean! Thanks!

  12. I was getting a Parse error: syntax error, unexpected T_STRING in inline-logo.svg.php on line 1. The issue was with the <?xml tag at the beginning of the svg and php allow shortcodes left on, so apache was reading it as <?phpxml. The way I got around it is to add: "php_value short_open_tag 0" (without the quotes) into the root htaccess file.

  13. Felicia B. on October 22, 2015 at 6:15 pm said:

    Brilliant & simple solution – Thanks, Galen!

    I modified the shortcode to be able to take the filename as an argument. For example, define shortcode in functions.php as follows:
    “`
    function add_inline_svg($atts, $content=null) {
    get_template_part(‘inline’, $content);
    }
    add_shortcode(‘addsvg’, ‘add_inline_svg’);
    “`
    …then use like so: `[addsvg]picture.svg[/addsvg]` to insert contents of inline-picture.svg.php.

  14. If you copy the code out, make sure to switch out the quote marks.

  15. How do you see fallbacks working with this method?

    Using preg_match and an if statement would be one way to detect older IE versions for example but if anyone else has any ideas?

    i would love to rely on just SVG but I still have clients who use IE7/8.

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop