Skip to content

Instantly share code, notes, and snippets.

@ian-svoboda-prom
Created April 17, 2023 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ian-svoboda-prom/b7a436d5397e007b7d8d5427465ff161 to your computer and use it in GitHub Desktop.
Save ian-svoboda-prom/b7a436d5397e007b7d8d5427465ff161 to your computer and use it in GitHub Desktop.
PHP functions to retrieve an SVG file and load it inline. Also supports adding new attributes to the SVG that aren't already there.
<?php
function get_html_attributes(array $atts) {
return array_reduce($atts, function($carry, $name) use($atts) {
$value = $atts[$name];
return "$carry $name=\"$value\"";
});
}
function get_svg( string $name, array $atts = [] ) : string {
$file = get_template_directory() . "/dist/images/$name.svg";
// Bail if the file can't be found
if( ! file_exists( $file ) ) {
return '';
}
$svg = file_get_contents( $file );
// Bail here if file_get_contents fails
if( $svg === false ) {
return '';
}
$new_atts = get_html_attributes( $atts );
return preg_replace( '/<svg/', "<svg $new_atts", $svg );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment