Member-only story

Inline SVG System in WordPress (or PHP) Development

Kevin
3 min readApr 10, 2021

--

SVG Icons

Have you ever needed to inline some SVGs in PHP, but found it rather bloated, un-readable, barely accessible, and non-modular?

If you are working on a PHP framework (especially WordPress), there is a more streamlined way to manage SVGs: store all SVG files on a folder, and reference them with a PHP function that can also modify the markup!

To clarify my reference to accessibility and the need to modify an SVG markup, there have been many cases where I needed an SVG to be accessible, and thus requiring extra attributes. A descriptive, accessible SVG should look something like this:

<svg ... aria-labelledby="phone-icon" role="img"><title id="phone-icon">Call Me Maybe</title><path ... ></svg>

But again, this is not only laborious to write, but also fill your PHP file with even more poor-readability codes!

TL;DR

There is a PHP function (below) called get_the_svg() that allows you to get an SVG file from a folder and process it for accessibility.

Use Cases for Inline SVG

  1. You need to use CSS to modify the internal SVG style, e.g. color or fill
  2. You need to reference certain elements within the SVG via JavaScript

Solution

There is a solution, however, by creating a PHP function that essentially does two things:

  1. Fetch an SVG file, and parse it as inline HTML code
  2. While doing so, add accessibility attributes as specified, or an aria-hidden="true" for purely decorative ones

The Setup

  1. Folder where the SVG files are located
  2. The Function
    Let’s call it get_the_svg() .
  3. PHP file where SVG would need to be displayed via the Function
    Let’s imagine that then end product would be <?php echo get_the_svg( 'phone', 'Call Me Maybe') resulting in inlining ‘phone’ SVG with accessibility title of ‘Call Me Maybe’

The Function

For this example, I will be using a WordPress + custom theme set up, where the SVG files are located on ./assets/icons/ folder relative to the theme’s…

--

--

Kevin
Kevin

Written by Kevin

0 Followers

Web Developer at Longbeard.

No responses yet

Write a response