Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

Let administrators upload SVG images

Administrators can upload SVG files to the media library. Other users can’t, because an SVG file can contain scripts.

  • Type PHP
  • Runs Everywhere (runs as WordPress loads)
  • Tested with WordPress 7.1
PHP
<?php

// Only users who may post unfiltered HTML (administrators). Upload only SVG
// files you made or trust.
add_filter(
	'upload_mimes',
	static function ( $mimes ) {
		if ( current_user_can( 'unfiltered_html' ) ) {
			$mimes['svg'] = 'image/svg+xml';
		}
		return $mimes;
	}
);

// PHP may report an SVG as plain text; tell WordPress what it really is.
add_filter(
	'wp_check_filetype_and_ext',
	static function ( $data, $file, $filename ) {
		if ( ! current_user_can( 'unfiltered_html' ) || 'svg' !== strtolower( pathinfo( (string) $filename, PATHINFO_EXTENSION ) ) ) {
			return $data;
		}
		$start = is_readable( $file ) ? (string) file_get_contents( $file, false, null, 0, 4096 ) : '';
		if ( false !== stripos( $start, '<svg' ) ) {
			$data['ext']  = 'svg';
			$data['type'] = 'image/svg+xml';
		}
		return $data;
	},
	10,
	3
);

In these packs

  • Content and media: Shortcodes, links, images and small design touches for the public site.

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.