-
-
Save davidwebca/0590c2ca2d9ddfa638eeb138fbd74d13 to your computer and use it in GitHub Desktop.
SVG helper functions for WordPress
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 | |
/** | |
* Include inline svg with + allow custom attributes as php function arguments | |
* | |
* Based on | |
* https://gist.github.com/kingkool68/6d72977fe8c82eeb9a85295ac3623cde#file-svg-functions-php | |
* | |
*/ | |
/** | |
* Helper function for fetching SVG icons | |
* | |
* @param string $icon Name of the SVG file in the icons directory. Allows .svg extension or not | |
* @return string Inline SVG markup | |
*/ | |
function wp_svg( $icon = '', $class = '', $attrs = array()) { | |
if ( ! $icon ) { | |
return; | |
} | |
$icon = preg_replace('/.svg$/', '', $icon); | |
$path = get_template_directory() . '/assets/icons/' . $icon . '.svg'; | |
$default_classes = [ | |
'icon', | |
'icon-' . $icon, | |
$class | |
]; | |
$defaults = [ | |
'class' => implode(' ', $default_classes) | |
]; | |
$attrs = wp_parse_args( $attrs, $defaults ); | |
return wp_get_svg( $path, $attrs); | |
} | |
/** | |
* Generic helper to modify the markup for a given path to an SVG | |
* | |
* @param string $path Absolute path to the SVG file | |
* @param array $args Args to modify attributes of the SVG | |
* @return string Inline SVG markup | |
*/ | |
function wp_get_svg( $path = '', $attrs = array() ) { | |
if ( ! $path ) { | |
return; | |
} | |
$defaults = [ | |
'role' => 'image', | |
'class' => '', | |
'aria-labelledby' => 'title' | |
]; | |
$attrs = wp_parse_args( $attrs, $defaults ); | |
$role_attr = $attrs['role']; | |
$class = $attrs['class']; | |
if ( is_array( $class ) ) { | |
$class = implode( ' ', $class ); | |
} | |
if ( file_exists( $path ) ) { | |
$svg = file_get_contents( $path ); | |
$svg = preg_replace( '/(width|height)="[\d\.]+"/i', '', $svg ); | |
$svg = str_replace( '<svg ', '<svg '. implode(' ', array_map(function ($k, $v) { return $k .'="'. esc_attr($v) .'"'; }, array_keys($attrs), $attrs)) .' ', $svg ); | |
return $svg; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment