3

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; ?>
2
  • 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". Commented Feb 12, 2020 at 14:00
  • I would think so too, but PHPCS with the latest WP Coding standards is "insisting" on escaping it, that's why I asked. I did, what @Tim Elsass suggested and used wp_kses on both.
    – Bonovski
    Commented Feb 13, 2020 at 5:33

2 Answers 2

2

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.

2

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 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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