Fix SVG icons not saving

GenerateBlocks allows you to insert your own SVG icons, which is great because you don’t have to rely on a pre-determined list of available icons.

However, SVG code can be dangerous. It can include <script> elements, which can lead to XSS vulnerabilities.

To mitigate that risk, we use DomPurify, which sanitizes your SVG code when you insert it, and when you save it. This prevents nasty things from ever making it into your content.

However, WordPress itself will not save SVG code unless your user has the unfiltered_html capability.

By default, everyone but the “author” role has this capability. The exception is within multi-site installs, where even administrators don’t have the ability to save unfiltered_html.

If you’re running into this issue, you can tell WordPress to allow these basic SVG tags/attributes.

add_filter( 'wp_kses_allowed_html', function( $tags, $context ) {
	if ( 'post' === $context ) {
		$tags['svg'] = array(
			'viewbox' => true,
			'filter' => true,
			'xmlns' => true,
			'class' => true,
			'preserveaspectratio' => true,
			'aria-hidden' => true,
			'data-*' => true,
			'role' => true,
			'height' => true,
			'width' => true,
		);

		$tags['path'] = array(
			'class' => true,
			'fill' => true,
			'd' => true,
		);

		$tags['filter'] = array(
			'id' => true,
		);
	}

	return $tags;
}, 10, 2 );

This code will allow the essential SVG tags/attributes, while continuing to disallow the dangerous bits.

We may add this to the plugin by default one day, but for now it seems like a decision best left up to the user.