Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add SVG support to a WordPress installation so images display properly in admin pages. https://core.trac.wordpress.org/ticket/26591

Add SVG support to WordPress

See https://core.trac.wordpress.org/ticket/26591 for background on this plugin.

Usage:

  • Make sure your .htaccess file is writable.
  • Add the plugin file to your /wp-content/plugins/ folder and activate, or to your /wp-content/mu-plugins folder.
  • Visit your Permalinks page in the Admin settings section and update your permalinks. This will refresh the .htaccess file with the SVG rules.
  • Check your Admin pages to make sure SVG images are now displaying properly.
<?php
/**
* Plugin Name: Add SVG Support
* Plugin URI: https://gist.github.com/morganestes/10066447
* Description: Adds SVG support to the `.htaccess` file so Chrome displays images in Admin correctly.
* Version: 0.1.0
* Author: Morgan Estes
* Author URI: http://www.morganestes.me
* License: GPLv2
*/
class MorganEstes_SVG {
/**
* Constructor to kick off the magic.
*/
public function __construct() {
$this->init_svg();
}
/**
* Add our functions inside the right hooks.
*/
public function init_svg() {
add_action( 'admin_init', array( $this, 'htaccess_writable' ) );
add_action( 'mod_rewrite_rules', array( $this, 'add_svg_htaccess' ) );
}
/**
* Show an admin notice if .htaccess isn't writable.
*
* @link https://github.com/rub1/lbrl/blob/master/lib/utils.php#L70
*/
function htaccess_writable() {
if ( ! is_writable( get_home_path() . '.htaccess' ) ) {
if ( current_user_can( 'administrator' ) ) {
add_action( 'admin_notices', create_function( '', "echo '<div class=\"error\"><p>" . sprintf( __( 'Please make sure your <a href="%s">.htaccess</a> file is writable ', 'roots' ), admin_url( 'options-permalink.php' ) ) . "</p></div>';" ) );
}
}
}
/**
* Adds the SVG ruleset to the install's `.htaccess` file.
*
* Since WordPress adds the permalinks to the .htaccess file,
* I'm hooking into the core mod_rewrite_rules action to
* copy my rules in at the same place.
*
* @param $rules
*
* @return string
*/
public function add_svg_htaccess( $rules ) {
if ( ! defined( 'FS_METHOD' ) ) {
define( 'FS_METHOD', 'direct' );
}
$svg_rules = <<<EOF
# Add SVG support to the server
AddType image/svg+xml svg
AddType image/svg+xml svgz
AddEncoding x-gzip .svgz
EOF;
return $rules . $svg_rules;
}
}
$morganestes_svg = new MorganEstes_SVG;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.