This assumes you're editing a WordPress theme which is the root of your VSCode workspace. In other words if your theme lived in /wp-content/themes/my-awesome-theme
. You would drag the directory my-awesome-theme
into VSCode and start editing files from there. This also assumes you're using Composer.
If this doesn't work for you check out https://www.edmundcwm.com/setting-up-wordpress-coding-standards-in-vs-code/ which details installing the PHP Code Sniffer tools globally instead of in a project.
We need to require dependencies in our project.
composer require --dev squizlabs/php_codesniffer
composer require --dev dealerdirect/phpcodesniffer-composer-installer
composer require --dev wp-coding-standards/wpcs
The Composer Installer package will automagically make PHPCS aware of coding standards/rulesets (aka WPCS). You should see the following added to your composer.json
file:
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
}
Let's make sure PHPCS is aware of the WPCS rules:
vendor/bin/phpcs -i
The installed coding standards are MySource, PEAR, PSR1, PSR2, PSR12, Squiz, Zend, PHPCompatibility, PHPCompatibilityParagonieRandomCompat, PHPCompatibilityParagonieSodiumCompat, PHPCompatibilityWP, WordPress, WordPress-Core, WordPress-Docs and WordPress-Extra
You should see WordPress
listed there. If so, you're good.
Add the phpcs.ruleset.xml
file to your project.
Install the PHP Sniffer & Beautifier VSCode extension.
Open a PHP file from your theme, add the following, and save the file:
$test = array(
'a' => 'b',
'cat' => 'dog',
);
You should see a warning that the array items aren't aligned. There is a squiggle under the '
in 'b',
. Right click and select Format Document. Your alignment issue should now be fixed:
$test = array(
'a' => 'b',
'cat' => 'dog',
);