Skip to content

Instantly share code, notes, and snippets.

@radist2s
Created December 30, 2015 10:14
Show Gist options
  • Save radist2s/7acb0ab4c7ccab2983a7 to your computer and use it in GitHub Desktop.
Save radist2s/7acb0ab4c7ccab2983a7 to your computer and use it in GitHub Desktop.
SVG embeding funtions
<?
function embed_svg($svg_path, $image_class = '', Array $attributes = array(), $is_abs_path = FALSE)
{
if (!$is_abs_path)
{
$image_path = get_template_directory() . '/static/img/' . trim($svg_path, ' /');
}
else
{
$image_path = $svg_path;
}
if (!is_readable($image_path))
{
throw new ErrorException('No image "' . $image_path . '""');
}
$attributes_list = array();
if ($attributes)
{
foreach ($attributes AS $key => $value)
{
$attributes_list[] = esc_attr($key) . '="' . esc_attr($value) . '"';
}
}
$attributes_list = implode(' ', $attributes_list);
$image = trim(file_get_contents($image_path));
if (defined('SVG_DEFS_INCLUDED'))
{
$matches = array();
if (preg_match('~<svg[\s\S]+viewBox="([\d\s\.]+?)"~iu', $image, $matches))
{
array_shift($matches);
$svg_path_parts = explode('/', $svg_path);
array_pop($svg_path_parts);
$svg_path_parts = array_slice($svg_path_parts, array_search('pages', $svg_path_parts) + 1);
array_push($svg_path_parts, basename($svg_path, '.svg'));
$svg_id = implode('--', $svg_path_parts);
ob_start();
?>
<svg viewBox="<?= esc_attr($matches[0]) ?>" class="<?= esc_attr($image_class) ?>" <?= $attributes_list ?> xmlns="http://www.w3.org/2000/svg">
<use xlink:href="#<?= esc_attr($svg_id) ?>" width="100%" height="100%"></use>
</svg>
<?
return ob_get_clean();
}
}
if ($image AND ($image_class OR $attributes_list))
{
$image = preg_replace('~^<svg\s+xmlns~iu', "<svg class=\"$image_class\" $attributes_list xmlns", $image);
}
return $image;
}
function embed_svg_defs($defs_path)
{
$image_path = trailingslashit(get_template_directory()) . $defs_path;
if (!is_readable($image_path))
{
return;
}
$svg = embed_svg($image_path, '', array(), true);
if (!defined('SVG_DEFS_INCLUDED'))
{
define('SVG_DEFS_INCLUDED', true);
}
return $svg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment