Drazen
Published 13th May 2024
PHP Code Sniffer with WordPress Coding Standard
Tired of WordPress core nagging you about coding style inconsistencies in your plugins or themes? Fear not! This guide will walk you through setting up PHP CodeSniffer (PHPCS) with the WordPress Coding Standard (WPCS). Get ready to write clean, consistent, and future-proof WordPress code that adheres to best practices. Let's dive in!
Setting up Composer
The first thing you need to do is install Composer if you don't have it already. I'm not going to go into great detail about how to install composer since it's already documented on their website.
After that, navigate to the root fo your project and create a composer.json
file (if you don't have it already) by typing composer init
.
WordPress Coding Standard
After you have installed Composer and have a composer.json
in your project root type the following commands:
composer config allow-plugins.dealerdirect/phpcodesniffer-composer-installer true
composer require --dev wp-coding-standards/wpcs
Custom Configuration File
Create a phpcs.xml
file in the project root. Here's an example configuration you can use as a template:
PHP Code Sniffer Configuration File for WordPress
Composer Scripts
In this example we have added two scripts: lint
and lint:fix
. The lint
command shows all linting errors and warnings present in the configured
files, while the lint:fix
command tries to automatically fix errors which
it can fix.
Important: Thelint:fix
command can't fix all commands thelint
command can find. These changes need to be fixed manually. Also: don't forget to add the .phpcs.cache folder to your .gitignore file.
{ "scripts": { "lint": "./vendor/bin/phpcs --standard=phpcs.xml", "lint:fix": "./vendor/bin/phpcbf --standard=phpcs.xml" } }
Additional Steps
Once you've completed the steps you're pretty much done. You can now use the scripts to check your code for inconsistencies and fix errors.
You could add the composer lint
command to your pre-commit hooks or to your CI/CD workflows to ensure that no un-linted code slips through the cracks.