How to Setup WordPress Coding Standards in VSCode

WordPress Coding Standards are documented in detail in WordPress Developer Handbook. Fortunately, WordPress offers a Github project, which maintains the WordPress Coding Standards rules and the tools needed to inspect and format the code (PHP Code Sniffer And Beautifier).

Please, note that WordPress Coding Standards have notable differences from PSR (PHP Standard Recommendation), for example:

  • snake case (my_function_name)
  • space around function arguments (myfunction ( 'foo' ))
  • long array syntax (array() instead of [])
  • and more

On your workstation

If you haven’t already, install Composer. Detailed instructions, you can find in this post.

Then, choose a folder in your workstation to set up the WordPress-Coding-Standards project. In my case, this folder is /data/projects/tools.

cd /data/projects/tools

git clone git@github.com:WordPress/WordPress-Coding-Standards.git

cd WordPress-Coding-Standards

composer install

With the above process:

  1. WordPress Coding Standards are installed in the directory WordPress-Coding-Standards.
  2. PHP_CodeSniffer is installed.
  3. WordPress Coding Standards are registered in the PHP_CodeSniffer configuration

Regarding (3) composer will notice you with the message:

PHP CodeSniffer Config installed_paths set to ../../../,../../phpcompatibility/php-compatibility,../../phpcsstandards/phpcsdevtools,../../phpcsstandards/phpcsextra,../../phpcsstandards/phpcsutils

VSCode

Install PHP Sniffer & Beautifier extension.

Configure extension

Use VSCode settings.json to apply the following settings:

    "phpsab.executablePathCBF": "/data/projects/tools/WordPress-Coding-Standards/vendor/squizlabs/php_codesniffer/bin/phpcbf",
    "phpsab.executablePathCS": "/data/projects/tools/WordPress-Coding-Standards/vendor/squizlabs/php_codesniffer/bin/phpcs",
    "phpsab.autoRulesetSearch": false,
    "phpsab.standard": "WordPress",
    "phpsab.snifferArguments": [
        "--ignore=*/wp-admin/*,*/wp-includes/*"
    ]

Remember to replace /data/projects/tools with your own path.

PHP Code Sniffer will automatically detect coding standard errors in PHP documents.

To fix a document (when possible) use Right Click ⟿ Format Document.

Ignore files from PHPCS inspection in VSCode

Use the phpsab.snifferArguments setting as mentioned above to ignore file patterns using the parameter--ignore:

Example

    "phpsab.snifferArguments": [
        "--ignore=*/path1/*,*/path2/*,*/path3/*"
    ]

See

Ignore PHPCS inspection in a certain line

// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
$attributes_encoded = base64_encode( $attributes );

Otherwise you get the message:

base64_encode() can be used to obfuscate code which is strongly discouraged. Please verify that the function is used for benign reasons.

Reference