Question

How do you escape these two examples? wc_price() wraps the already escaped $product_price in p and span tags with currency symbol.

$product_price = $product->get_price();

<p><?php echo wc_price( esc_html( $product_price ) ); ?></p>

The next one outputs the complete image with all attributes: src, srcset, alt, etc.

$product_img = $product->get_image();

<?php echo $product_img; ?>
Was it helpful?

Solution

For the first example, a lot of people will use wp_kses_post to handle basic HTML output from wrapper functions. It's a shortcut for some basic attributes and tags using wp_kses. You could use this function where you specify allowed tags and attributes that can pass through for the second example.

OTHER TIPS

My opinion is that you wouldn't. wc_price() and $product->get_image() are both escaped further upstream. In the WordPress Coding Standards sniffs for PHPCS, these would be referred to as "auto escaped functions".

Double escaping by putting wp_kses_post() on everything that's already escaped, just to satisfy code sniff, is a waste of resources and not actually doing anything to solve the problem that the sniffing is supposed to solve in the first place.

The reason PHPCS is flagging these lines even though they're escaped is because the WP Coding standards don't know about 3rd-party functions. If your project is using them, or has its own auto-escaped functions, you should configure your project's rules to cover them. For example, adding this to your projects phpcs.xml file will stop PHPCS complaining about wc_price() not being escaped wherever it's used:

<rule ref="WordPress.Security.EscapeOutput">
    <properties>
        <property name="customAutoEscapedFunctions" type="array" value="wc_price,"/>
    </properties>
</rule>

customAutoEscapedFunctions doesn't support class methods, so to satisfy $product->get_image(); you would use an inline comment:

$product_img = $product->get_image();

echo $product_img; // phpcs:ignore WordPress.Security.EscapeOutput 
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top