Skip to content

Validate WordPress PHP coding standard using PHPCS

Coding standards guide the programmers to write code that can be easily read by other developers to understand every part of it effortlessly. So WordPress invent their own coding standard to make consistent between all developer’s code. In this article, we will discuss PHP Coding Standards and how we can verify our codes using PHPCS.

Install PHPCS

We need three composer package to run the coding standard tests. Here is how my composer.json file looks like.

  "require-dev": {
    "dealerdirect/phpcodesniffer-composer-installer": "*",
    "wp-coding-standards/wpcs": "*",
    "phpcompatibility/phpcompatibility-wp": "*"

After adding composer.json file we need to run composer update command to install packages in our local directory. When composer packages installed then we need to run the following command.

vendor/bin/phpcs -i

If this command output like below then everything properly installed.

The installed coding standards are PEAR, Zend, PSR2, MySource, Squiz, PSR1, PSR12, WordPress, WordPress-Extra, WordPress-Docs, WordPress-Core, PHPCompatibilityParagonieRandomCompat, PHPCompatibilityParagonieSodiumCompat, PHPCompatibilityWP and PHPCompatibility

Now add .phpcs.xml file to your project root directory, this file will set our standard when we will run vendor/bin/phpcs.


<ruleset name="WordPress Coding Standards based custom ruleset for your plugin">
	<description>Generally-applicable sniffs for WordPress plugins.</description>
	<arg value="sp"/> 
	<arg name="basepath" value="./"/>
	<arg name="colors"/>
	<arg name="extensions" value="php"/>
	<arg name="parallel" value="8"/>
	<config name="testVersion" value="5.3-"/>
	<rule ref="PHPCompatibilityWP"/>
	<config name="minimum_supported_wp_version" value="4.6"/>
	<rule ref="WordPress"/>
	<rule ref="WordPress.WP.I18n">
			<property name="text_domain" type="array" value="my-plugin"/>
	<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
			<property name="blank_line_check" value="true"/>

Now run coding test using the PHPCS command.


Various Tweaks

Ignore a single line:
You can ignore a single line using the phpcs:ignore comment. This comment will ignore the line that the comment is on.

// phpcs:ignore
$foo = [1,2,3];
bar($foo, false);
$foo = [1,2,3]; // phpcs:ignore
bar($foo, false);

Ignoring parts of a file:
Sometimes have to break coding standard, To stop PHPCS generating errors for our code, we can wrap it in special comments.

$xmlPackage = new XMLPackage;
// phpcs:disable
$xmlPackage['error_code'] = get_default_error_code_value();
// phpcs:enable

Exclude any rule globally:
Let’s change a rule for WordPress standard globally through .phpcs.xml


<rule ref="WordPress">
	<exclude name="WordPress.Files.FileName" />


Leave a Reply

Your email address will not be published.

twelve − 10 =