Created
April 17, 2023 10:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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