Introdution

Coding Standards are collections of best practices for writing codes, most likely you will find them in the documentation of your favorite programming language.

In WordPress (in this case a CMS, not a programming language) is no different, we can find through this link a collection of rules and best practices to develop themes and plugins.

In this article I will show you how to configure Visual Studio Code to format your code and always make it beautiful according to the WordPress Coding Standards.

Prerequisites

Make sure you have the following installed on your computer:

  • Visual Studio Code (obvioulsy)
  • PHP
  • Composer

Let’s start

After ensuring that all the prerequisites have been met, let’s go to what matters:

# Installs required version of PHP CodeSniffer, according to WPCS requirements
$ composer global require squizlabs/php_codesniffer:3.4.*

# Make it globally accessible in your PATH
$ export PATH=~/.composer/vendor/bin:$PATH

# Verify that it's installed correctly by running phpcbf --version.
$ phpcbf --version

If you received permission error when installing a dependency, set the composer permissions

Now that we have been able to use phpcbf and phpcs, we need to configure what Coding Standard we want:

# Clone the WordPress standards repository:
$ git clone -b master https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards.git wpcs

# Add its path to the PHP_CodeSniffer configuration:
$ phpcbf --config-set installed_paths /path/to/wpcs

If we stop here, we’ll be able to format our code through the command line:

phpcbf --standard=WordPress --extensions=php /path/to/php/files

But what we want, is with a simple keyboard shortcut, make it happen directly from our code editor.

To achieve this, we need to install the phpcbf extension in the Visual Studio Code (available at this link), and configure the following:

{
    "phpcbf.executablePath": "~/.composer/vendor/bin/phpcbf",
    "phpcbf.standard": "WordPress",
}

Now, using a Visual Studio Code shortcut (or context menu), we have already been able to meet the WordPress code pattern requirements.

Formatting code in Visual Studio Code with WordPress Coding Standards