Skip to content
Advertisement

Prepend SVG icon before WooCommerce message

I want to prepend an SVG icon to the Add to Cart message in WooCommerce, but for some reason the SVG is not shown in the message.

I have the following code in my functions.php file:

function update_add_to_cart_message($message, $product_id) {
    $icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"></path><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path></svg>';
    $message = $icon . $message;
    return $message;
}
add_filter('wc_add_to_cart_message_html', 'update_add_to_cart_message', 10, 2);

If I replace the svg with something like $icon = '<span>Test</span>';, it works fine.

Why isn’t this working and what do I need to do to fix it? I could of course update the WooCommerce template file, but I prefer not to.

Advertisement

Answer

WooCommerce is using wp_kses() function with wp_kses_allowed_html('post') context to filter notices https://docs.woocommerce.com/wc-apidocs/source-function-wc_add_notice.html#220. post context doesn’t have <svg> and <path> tags whitelisted, this is the reason why your svg code is getting stripped.

As a blunt workaround, you can hook to wp_kses_allowed_html and add svg-related tags and attributes to whitelist for post context:

function wp_kses_allowed_html_63014342( $allowedposttags, $context ) {
    if ( $context === 'post' ) {
        $allowedposttags['svg']  = array(
            'xmlns'   => true,
            'viewbox' => true,
        );
        $allowedposttags['path'] = array(
            'd'    => true,
            'fill' => true,
        );
    }
    return $allowedposttags;
}

add_filter( 'wp_kses_allowed_html', 'wp_kses_allowed_html_63014342', 10, 2 );

Note this would allow these tags for everything that is using post context though.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement