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.
Dependencies
We will need to have the following installed on your computer:
- Visual Studio Code (obviously)
- Aptitude packages
- Composer
Let’s start
Step 1 – Installing the Dependencies
First, update the package manager cache by running
sudo apt updateNow, let’s install the dependencies. Everything can be installed with the following command:
sudo apt install curl php-cli php-mbstring php-xmlwriter git unzipStep 2 – Installing Composer
To download and install Composer, just run this code:
cd ~ && curl -sS https://getcomposer.org/installer -o composer-setup.php && php composer-setup.php --install-dir=/usr/local/bin --filename=composer && rm composer-setup.phpTo test your installation, run:
composerStep 3 – Installing PHP CodeSniffer
After installing all dependencies, let’s start the process.
First, install the required PHP CodeSniffer version according to WPCS requirements:
composer global require squizlabs/php_codesniffer:3.4.*If you received a permission error when installing a dependency, set the composer permissions:
sudo chown -R $USER ~/.config/composer/Now, make it globally on your $PATH:
export PATH=~/.config/composer/vendor/bin:$PATHAnd finally, verify that’s working:
phpcbf --versionStep 4 – Setting up the WordPress Coding Standards
Now that we have been able to use phpcbf and phpcs, we need to configure what Coding Standard we want:
Clone the WordPress Coding Standards repository into your users folder:
cd ~ && git clone -b master https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards.git wpcsAdd the WPCS path to PHP_CodeSniffer settings
phpcbf --config-set installed_paths /path/to/wpcsIf we stop here, we’ll be able to format our code through the command line:
phpcbf --standard=WordPress --extensions=php /path/to/php/filesBut what we want, is with a simple keyboard shortcut, make it happen directly from our code editor.
Step 5 – Setting up Visual Studio Code to use WPCS
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": "~/.config/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.
