1

I'm trying to output an SVG file in a template, and PHPCS is telling me I need to escape the output. So I tried with KSES and it doesn't seem to want to include the viewbox attribute.

 $allowed_html = array(
  'svg' => array(
    'xmlns' => array (),
    'viewBox' => true
  ),
  'path' => array(
    'd'=> array(),
  ),
);

 wp_kses(file_get_contents( $logo ), $allowed_html ) 

Any ideas why this doesn't work?

2

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 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.