How Flexible are the WordPress Coding Standards for PHPCS?

In my WordPress workflow I use Gulp and have a task that runs my PHP files through PHPCS using the WordPress coding standards tests (https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards).

While writing my comments.php file, I have run across the following error:

Expected next thing to be an escaping function (see Codex for ‘Data Validation’), not ‘_x’

This is being generateds by the following line of code:

printf( _x( '1 Comment on “%s”', 'Comments Title', 'jldc' ), get_the_title() );

I pretty much reused the same line from the Twenty Sixteen theme that ships with WordPress. Out of curiosity I ran PHPCS against Twenty Sixteen’s comments.phpfile and got the same errors.

Now, I can easily use esc_html_x() instead of _x as I presume that is what the guidelines want me to use. But what about this line:

printf(
   _nx(
      '%1$s Comment on “%2$s”',
      '%1$s Comments on “%2$s”',
      $comment_count,
      'Comments Title',
      'theme-text-domain'
      ),
      number_format_i18n( $comment_count ),
      get_the_title()
   );

Or can I simply ignore the error?

2 Answers
2

Consider something like the following:

echo esc_html(
      sprintf(
         _nx(
               '%1$s Comment on “%2$s”',
               '%1$s Comments on “%2$s”',
               $comment_count,
               'Comments Title',
               'theme-text-domain'
         ),
         number_format_i18n( $comment_count ),
         get_the_title()
      )
);

Where you build the entire string with sprintf and escape that.

The coding standards are clear that you should always escape output, and do so as late as possible. As you’ve noticed, however, even the default theme doesn’t adhere to them exactly.

Leave a Comment