WordPress theme plugin unit test with PHPCS – PHP_CodeSniffer

In this article, I will show how to run PHP unit testing for WordPress themes and plugins using PHP_CodeSniffer.

Let’s install WordPress coding standards with the composer.
Install it outside your theme/plugin directory. I’m installing it in var/www/html
composer create-project wp-coding-standards/wpcs --no-dev

Running this command will:
1. Install WordPress standards into wpcs directory.
2. Install PHP_CodeSniffer.
3. Register WordPress standards in PHP_CodeSniffer configuration.
4. Make phpcs command available from wpcs/vendor/bin.

Now cd into to wpcs directory on your terminal, rename phpcs.xml.dist.sample file to phpcs.xml.dist . Then go to WordPress/ruleset.xml and edit this file in an editor. Now exclude all assets (js, css) files inside ruleset , like below.


Now come back to wpcs repo and run the command below. you can check the full plugin or check specific file like: pluginName/file.php .

vendor/bin/phpcs --standard=WordPress ../wordpress/wp-content/plugins/pluginName
Disbelief Reaction GIF

Here I am testing my plugin DevTo articles on WP. PHPCS is showing all file errors/warnings in a Table. The table contains:
1. Line Number
2. Status: Error/Warning
3. Should remove or not
4. Message

You can fix all errors manually, if you are a beginner then you should fix all manually. But on a production level, you can fix minor errors/warnings automatically with phpcbf. Just run the command with phpcbf.
vendor/bin/phpcbf --standard=WordPress ../hello/wp-content/plugins/devto-articles-on-wp

Cheers Stay Home GIF by Mena

5 1 vote
Article Rating