Escaping SVG with KSES

Found your question as I was searching for an answer. I tried experimenting a bit more with wp_kses and found that lower-casing viewbox in the arguments seems to fix the issue. You don’t have to put the actual attribute on the SVG in lowercase, just the wp_kses() argument.

This may be more than you need, but here’s what I’m using right now:

<?php
$kses_defaults = wp_kses_allowed_html( 'post' );

$svg_args = array(
    'svg'   => array(
        'class' => true,
        'aria-hidden' => true,
        'aria-labelledby' => true,
        'role' => true,
        'xmlns' => true,
        'width' => true,
        'height' => true,
        'viewbox' => true, // <= Must be lower case!
    ),
    'g'     => array( 'fill' => true ),
    'title' => array( 'title' => true ),
    'path'  => array( 'd' => true, 'fill' => true,  ),
);

$allowed_tags = array_merge( $kses_defaults, $svg_args );

echo wp_kses( $rich_text_that_might_include_SVGs, $allowed_tags );

Leave a Comment

error code: 523