Site icon Treehouse Blog

The Perfect WordPress Inline SVG Workflow

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!

Exit mobile version