Skip to content

Instantly share code, notes, and snippets.

@aurooba
Last active February 17, 2024 23:33
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aurooba/98b4f3530a55b546b76bef2c6ea4c179 to your computer and use it in GitHub Desktop.
Save aurooba/98b4f3530a55b546b76bef2c6ea4c179 to your computer and use it in GitHub Desktop.
Helper function to inline your SVG files in a WordPress theme or plugin and optionally also update the attributes. Only works with WordPress 6.2 and onwards. Blog post with explanation and usage instructions: https://aurooba.com/inline-svgs-in-your-wordpress-code-with-this-helper-function/
<?php
/**
* Get an SVG file from the imgs/ folder in the theme, update its attributes if necessary and return it as a string.
*
* @author Aurooba Ahmed
* @see https://aurooba.com/inline-svgs-in-your-wordpress-code-with-this-helper-function/
*
* @param string $filename The name of the SVG file to get.
* @param array $attributes (optional) An array of attributes to add/modify to the SVG file.
* @param string $directory (optional) The directory to look for the SVG file in, defaults to 'imgs'.
* @return string|WP_Error The SVG file as a string or a WP_Error object if there was an error.
*/
function get_svg( $filename, $attributes = array(), $directory = 'imgs' ) {
// Get the SVG file.
$svg = file_get_contents( get_stylesheet_directory() . '/' . $directory . '/' . $filename . '.svg' );
$errors = new WP_Error();
// If there was an error retrieving the SVG file, return a WP_Error object.
if ( ! $svg ) {
$svg_error_message = sprintf(
/* translators: %1$s: SVG file name, %2$s: SVG directory */
__( 'There was an error retrieving the SVG file "%1$s" from the "%2$s" directory.', 'yourdomain' ),
$filename . '.svg',
$directory
);
$errors->add(
'svg_file_not_found',
$svg_error_message,
array(
'svg_file' => $filename . '.svg',
'svg_directory' => $directory,
)
);
return $errors;
}
// Initialize the SVG tag processor.
$update_svg = new WP_HTML_Tag_Processor( $svg );
$update_svg->next_tag( 'svg' );
// If there are attributes to add, add them.
if ( ! empty( $attributes ) ) {
foreach ( $attributes as $attribute => $value ) {
// If the attribute is 'class', add the class to the SVG file without overwriting the existing classes.
if ( 'class' === $attribute ) {
$update_svg->add_class( $value );
continue;
}
// Otherwise, set/update the attribute with the new value
$update_svg->set_attribute( $attribute, $value );
}
}
// Return the SVG string.
return $update_svg->get_updated_html();
}
@szepeviktor
Copy link

A useful wrapper.

/**
 * Print an SVG file
 *
 * See the documentation of get_svg()
 */
function print_svg( $filename, $attributes = array(), $directory = 'imgs' ) {
    print get_svg( $filename, $attributes, $directory );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment