Format Php Code in Visual Studio Code (WordPress Coding Standards)

Visual Studio Code is an awesome modern free code editor and it does a great job at developing javaScript-based applications. It has built-in support for JavaScript IntelliSense, debugging, formatting and many other advanced language features. “Wait, I am here for the PHP part“, you will say. Well, Visual Studio Code is not only about javaScript. In fact, with just a little customization, Visual Studio Code can also provide great support for many other languages or frameworks, including PHP and WordPress. However, it is not (yet) widely adopted by professional php developers, many of whom still prefer to use paid IDE-s such as PhpStorm. (nothing wrong with that) Apart from the fact that it is free, the other big advantage of Visual Studio Code is that it is very lightweight and at the same time highly customizable, thanks to thousands of community-created VS Code extensions. This means that, with a little patience and some tweaks, you can make your copy of VSC your best friend in software development.

Out of the box, Visual Studio Code provides basic features for PHP development such as syntax highlighting, bracket matching, IntelliSense, however, you will soon notice that it is far from perfect. As a WordPress theme developer, I have struggled for a long time for not being able to properly format php code in my WordPress themes. I literally tried all VSC extensions, however, I could not find a single one that did what it needed to – properly format php code as per WordPress coding standards. For example, the popular PHP formatter VSC extension formats the opening bracket of a fucntion at a new line:

function test()
{

}

While the opening bracket should stay on the same line.

Like this:

function test() {

}

This can drive a developer crazy! There is nothing worse in programming than a broken code formatter. There is even Stackoverflow thread about this insanity: VScode formatter, keep open bracket at same line (PHP). While the provided answer fixed the open bracket formatting issue, the code output was still far from being properly formatted. For example, by WordPress coding standards, you need to put a space on both sides of a variable in function parentheses (round brackets).

function test( $wp_customize ) {

}

Nothing like that was happenng after the “code formatting”.

In fact, the end result looked more like this:

function test($wp_customize) 
{

}

I was at the point to give up, delete all php formatting extensions and continue to manually format each line of code I write, when I came across an article that literally changed my programming life: How to set up WordPress Coding Standards in Visual Studio Code. It takes some time to install and configure it, but it is totally worth it. At the end of this tutorial, with a simple key combination (Shift + Alt + F), you will be able to format php code like a pro and you will also get as an option php sniffer, a language diagnostics tool to check against WordPress development requirements. Now, enough talking, lets tidy up our code!

Install PHP Code Sniffer

To properly format php code in Visual Studio Code, you first need to install php code sniffer on your PC. The easiest way to install it is with Composer. You can download and install Composer for Windows here. After that, in cmd, type:

composer require --dev squizlabs/php_codesniffer

You can also install it globally, by running:

composer global require "squizlabs/php_codesniffer=*"

Afer that, you can check if phpcs is installed by running the following command in cmd:

phpcs -i

The command will give you a list of the default coding standards. To add WordPress coding standards, you can install them via composer:

composer require --dev wp-coding-standards/wpcs
composer require --dev dealerdirect/phpcodesniffer-composer-installer

The second command should automatically link the WordPress coding standards to phpcs, however you may also need to do it manually, by locating the wpcs folder. Run the following command (replace {Username} with the correct profile name, e.g. John):

C:\Users\{Username}\AppData\Roaming\Composer\vendor\bin\phpcs --config-set installed_paths C:\Users\{Username}\wpcs

Now, when you run again the phpcs -i info command, you should see the WordPress coding standards in the list of installed coding standards.

Environment Variables

If you use Windows, you should double check whether php sniffer has been added to your list of environmental variables. In the search menu, type settings and then in the settings search bar type “env”, then click at “edit the system environment variables” => environment variables. From the system variables bar double click on Path and add an entry abouth php sniffer if it is missing. It should look something like this:

Environmental variables

Code Sniffer config file

You also need to check if you have CodeSniffer.conf file inside squizlabs/php_codesniffer folder. If not, create one and add the path to the WordPress coding standards:

CodeSniffer.conf

<?php
 $phpCodeSnifferConfig = array (
  'installed_paths' => 'C:\Users\Nasko\wpcs',
)
?>

Integrate WordPress Coding Standards to Visual Studio Code

Finally, we need to install a VSC extension that works with PHP Sniffer: PHP Sniffer & Beautifier. This extension works as both sniffer and beautifier and you can choose whether to use the sniffer or not. Here is the configuration I am using. Go to File => Preferences => Settings => Extensions => Edit in Settings.json and paste the following properties:

{
    "phpsab.snifferEnable" : false,
    "phpsab.autoRulesetSearch": false,
    "phpsab.executablePathCBF": "C:\Users\{Profile}\AppData\Roaming\Composer\vendor\squizlabs\php_codesniffer\bin\phpcbf.bat",
    "phpsab.executablePathCS": "C:\Users\{Profile}\AppData\Roaming\Composer\vendor\squizlabs\php_codesniffer\bin\phpcs.bat",
    "[php]": {
        "editor.defaultFormatter": "valeryanm.vscode-phpsab"
    },
    "extensions.ignoreRecommendations": false,
    "phpsab.snifferShowSources": true,
    "phpsab.standard": "WordPress",
    "phpsab.allowedAutoRulesets": [
        ".phpcs.xml",
        ".phpcs.xml.dist",
        "phpcs.xml",
        "phpcs.xml.dist",
        "phpcs.ruleset.xml",
        "ruleset.xml"
    ],
    "files.autoSave": "afterDelay",
    "beautify.config": ""
}

Do not forget to replace the executable path urls to your own. Now, if all went well, when you reload VSC, right click on any php file and choose “Format document”, it should finally give your code the justice it deserves.

Literature:

1. How to set up WordPress Coding Standards in Visual Studio Code

2. Setting up WordPress Coding Standards for your Site, Theme, or Plugin using VS Code

Leave a Reply

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