
SVGs on WordPress and for icons
Uploading SVGs to the media library
Add the below script to the functions file, or consider using a plugin like ‘SVG support’.
<?php function allow_new_mime_type($mimes) { $mimes['svg'] = 'image/svg+xml'; return $mimes; } add_filter( 'mime_types', 'allow_new_mime_type' );
Using SVGs in the Theme
As an image
<img src="your.svg" alt="Some alt tag">
In CSS as a background image
.your-svg { background-image: url(your.svg); } /* Inline */ .your-svg { background-image: url("data:image/svg+xml;utf8,<svg >...</svg>"); }
Note: To make a date: image url use a url encoder for SVGs.
Inserting a SVG file inline using php
<?php echo file_get_contents( get_stylesheet_directory_uri() . '/your.svg' ); <?php /* As a function: */ function load_icon( $file ) { $svg_folder = '/svg-icons/'; if ( file_exists( get_stylesheet_directory() . $svg_folder . $file . '.svg' ) ) { return file_get_contents( get_stylesheet_directory_uri() . $svg_folder . $file . '.svg' ); } return ''; } ?> <?php echo load_icon('your-icon'); ?>
Note: Each SVG is a separate http request so doing this for many SVG files might not be a great idea.
Accessibility
<a href="twitter.com..." target="_blank" rel="nofollow noopener noreferrer" aria-label="Twitter"> <span class="icon" aria-hidden="true"><?php echo load_icon('twitter'); ?></span> </a> /* or */ <a href="twitter.com..." target="_blank" rel="nofollow noopener noreferrer"> <span class="icon" aria-hidden="true"><?php echo load_icon('twitter'); ?></span> <span class="screen-reader-text">Twitter</span> </a>