Setting up PHP_CodeSniffer & Auto Formatter for WordPress Development in Visual Studio Code

Increase your WordPress Code Quality automagically.

1. Install Composer.

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.

Installed it using the official doc: Introduction – Composer (getcomposer.org)

2. Install PHP_CodeSniffer and WordPress Coding Standards for PHP_CodeSniffer

PHP_CodeSniffer is a set of two PHP scripts;

1. phpcs is a script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard.

2. phpcbf is a script to automatically correct coding standard violations.

 

Fire up your terminal and type these commands.

composer global require squizlabs/php_codesniffer wp-coding-standards/wpcs

this will install both the php_codesniffer and wp-coding-standard in to your local machine. After that, we need to add the wp-coding-standard to the list of phpcs standards. Use the below command to add. ( Make sure you give the absolute path for the wpcs standard installed location, by default it will install inside the .composer/vendor folder )

phpcs --config-set installed_paths ~/.composer/vendor/wp-coding-standards/wpcs

if phpcs command not working, then make sure you add the .composer/vendor/bin folder to your $PATH.

I am using zsh as my shell and this is what I add to my .zshrc file,

export PATH=$HOME/.composer/vendor/bin:$PATH

( this step is optional ) After all setup, you can run the phpcs -i command and confirm that wp-coding standard is added.

3. Configuring vscode.

To do so, we need two extensions.

  1. phpcs by Ioannis Kappas phpcs – Visual Studio Marketplace
  2. PHP Sniffer by wongjn PHP Sniffer – Visual Studio Marketplace

After installing those extensions, we need to configure it for linting and autoformatting, this is the configuration I used, you can copy paste it along with your vscode settings.

    // PHPCS
    "phpcs.enable": true,
    "phpcs.standard": "WordPress",
    // PHP Sniffer
    "phpSniffer.standard": "WordPress",
    "phpSniffer.autoDetect": true,
    "phpSniffer.run": "onSave",
    "phpSniffer.executablesFolder": "/Users/YOURUSERNAME/.composer/vendor/bin",
    "[php]": {
        "editor.defaultFormatter": "wongjn.php-sniffer"
    },

For the ‘phpSniffer.executablesFolder’ make sure you give the absolute path for phpcs folder, in my case it is inside the Users/YOURUSERNAME/.composer/vendor/bin folder, make sure you change the YOURUSERNAME to your username.

4. In Action.

Now when you type it’ll lint the code, and when you save it’ll auto format it to match the WordPress coding standards. 🙂

Share your love
Joe

Joe

Your friendly neighbourhood WordPress guy!

Articles: 3

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *