I’ve been using PHP_CodeSniffer and the WordPress Coding Standards sniffs in Visual Studio Code to help me avoid issues and follow the standards.

Occasionally, though, I’ll get an error from a sniff that is either over-vigorous or I can’t comply with for reasons outside of my control. A common case is when I’m working with a third-party API, and they use camel-case variable names. WPCS objects, but I don’t have a choice in the matter.

The advice that’s given is to use a // phpcs:ignore comment to override the particular sniff. I do this, and like to make it as specific as possible to prevent the suppression of other issues, but it’s not always obvious to me how to build the tree to ignore.

That’s why I’m documenting it here! It’ll definitely help me out in the future, and maybe it’ll help you, too. 🙂

Let’s take the case I gave above as an example: I have an object property coming from an API and the property name is ResultCode. WPCS objects because it’s not in “valid snake case.” Specifically, it throws this error: Object property "$ResultCode" is not in valid snake_case format, try "$result_code"

In order to find the specific string I need to stick behind // phpcs:ignore to avoid getting that specific error but not miss any others, I search the WordPress-Coding-Standards GitHub repo.

GitHub offers some powerful searching options, and I use the repo: and path: options to quickly drill down to the results I need. I combine the options with the static part of the error to find the specific sniff that’s objecting. In this case, that means I use the following search: repo:WordPress/WordPress-Coding-Standards path:/WordPress/Sniffs is not in valid snake_case format

This search leads me to line 172 (at this writing) of WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php. Using a combination of the file, its path, and the specific $error_name (UsedPropertyNotSnakeCase) on 173, I can build my ignore string. This is what it looks like: // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase

As you can see, it’s WordPress + the name of the directory under “Sniffs” + the name of the file (without “Sniff.php”) + the $error_name, each separated by a .. This seems a touch convoluted to me, but at least I understand it enough to reliably follow it, rather than having to rely on blog posts where other people spell out the exact comment I need for every different error.

One note: not all specific errors use the $error_name variable. In that case, I just end with the name of the file. For instance, to suppress an error about using date() (when I’m using it for a very good reason, in my defense!), I’m using // phpcs:ignore WordPress.DateTime.RestrictedFunctions

Leave a Comment





This site uses Akismet to reduce spam. Learn how your comment data is processed.