How to use PHPCS with WordPress Coding Standards

Install PHPCS with WordPress Coding Standards 3 through Composer, add a ruleset that works, fix what phpcbf can, and run the same check in GitHub Actions.

On this page
  1. Install it in your project
  2. Or install it once for every project
  3. Add a ruleset
  4. Run it
  5. Add Composer scripts
  6. Run it on every push

When I review plugins for WordPress.org, the same few problems come back again and again. Output that isn’t escaped. A $_GET value used without being sanitized. A function called show_greeting() with no prefix, free to clash with any other plugin that picked the same name.

Every one of them is something PHPCS would have flagged before the plugin was ever submitted.

PHP_CodeSniffer (PHPCS) checks PHP files against a set of rules. The WordPress Coding Standards (WPCS) project gives it the WordPress rules: escaping, sanitizing, prefixes, text domains, and the spacing style WordPress core uses.

I rewrote this post because the first version had two problems. Its global install step isn’t supported by WPCS 3 anymore, and one of its XML samples had a broken tag. Everything below I ran this week with PHPCS 3.13.6 and WPCS 3.4.1.

Install it in your project

I install it per project, so everyone who works on the plugin gets the same versions. From the plugin folder:

Shell
composer config allow-plugins.dealerdirect/phpcodesniffer-composer-installer true
composer require --dev wp-coding-standards/wpcs:"^3.0"

That second command pulled in five packages for me: PHPCS itself, WPCS, PHPCSUtils, PHPCSExtra, and the Composer installer plugin. The installer is the one that tells PHPCS where the WordPress rules live. Its last line of output was:

Code
PHP CodeSniffer Config installed_paths set to ../../phpcsstandards/phpcsextra,../../phpcsstandards/phpcsutils,../../wp-coding-standards/wpcs

The first command matters. Without it, Composer stops with “dealerdirect/phpcodesniffer-composer-installer contains a Composer plugin which is blocked by your allow-plugins config”, and nothing gets installed.

Check that PHPCS sees the rules:

Shell
vendor/bin/phpcs -i
Code
The installed coding standards are MySource, PEAR, PSR1, PSR2, PSR12, Squiz, Zend, Modernize, NormalizedArrays, Universal, PHPCSUtils, WordPress, WordPress-Core, WordPress-Docs and WordPress-Extra

Terminal output of phpcs -i listing the installed coding standards, including WordPress, WordPress-Core, WordPress-Docs and WordPress-Extra

Two things to know here. PHPCS 4 is out, but WPCS 3.4.1 requires PHPCS ^3.13.5, so Composer installs the 3.x line. And the Composer package is still called squizlabs/php_codesniffer, even though the project now lives under PHPCSStandards on GitHub.

Or install it once for every project

If you want phpcs on any folder without adding it to each project, install it globally:

Shell
composer global config allow-plugins.dealerdirect/phpcodesniffer-composer-installer true
composer global require --dev wp-coding-standards/wpcs:"^3.0"
composer global config bin-dir --absolute

The last command prints the folder that holds phpcs and phpcbf. Add it to your PATH.

You don’t need phpcs --config-set installed_paths anymore. The WPCS readme says Composer is the only supported way to install it since 3.0, because WPCS 3 also needs PHPCSUtils and PHPCSExtra registered. Pointing PHPCS at the WPCS folder by hand leaves those two out.

Add a ruleset

Without a ruleset, you have to pass --standard=WordPress on every run. With one in the project root, PHPCS finds it on its own. This is the file I tested:

XML
<?xml version="1.0"?>
<ruleset name="My Plugin">
	<description>Coding standards for My Plugin.</description>

	<!-- What to check. -->
	<file>.</file>
	<exclude-pattern>/vendor/*</exclude-pattern>
	<exclude-pattern>/node_modules/*</exclude-pattern>
	<exclude-pattern>*.min.js</exclude-pattern>

	<!-- Show progress and sniff codes, check PHP files only, run 8 files at a time. -->
	<arg value="ps"/>
	<arg name="extensions" value="php"/>
	<arg name="basepath" value="."/>
	<arg name="parallel" value="8"/>

	<!-- WordPress includes WordPress-Core, WordPress-Docs and WordPress-Extra. -->
	<rule ref="WordPress"/>

	<!-- The oldest WordPress version the plugin supports. -->
	<config name="minimum_wp_version" value="6.7"/>

	<!-- Flag strings that use the wrong text domain. -->
	<rule ref="WordPress.WP.I18n">
		<properties>
			<property name="text_domain" type="array">
				<element value="my-plugin"/>
			</property>
		</properties>
	</rule>

	<!-- Flag functions, classes and hooks that are missing the plugin prefix. -->
	<rule ref="WordPress.NamingConventions.PrefixAllGlobals">
		<properties>
			<property name="prefixes" type="array">
				<element value="my_plugin"/>
			</property>
		</properties>
	</rule>
</ruleset>

Save it as .phpcs.xml.dist and commit it. PHPCS looks for .phpcs.xml first, then phpcs.xml, then the .dist versions, so anyone on the team can keep a local .phpcs.xml with their own tweaks without touching the shared file.

Change my-plugin to your text domain and my_plugin to your prefix. minimum_wp_version is the oldest WordPress your plugin supports. WPCS uses it to decide which deprecated functions, classes and parameters to flag, and which newer alternatives it can suggest.

You only need <rule ref="WordPress"/>. It already includes WordPress-Core, WordPress-Docs and WordPress-Extra, so listing all four runs the same rules.

If your team doesn’t write Yoda conditions ('admin' === $name instead of $name === 'admin'), swap the WordPress line for this:

XML
<rule ref="WordPress">
	<exclude name="WordPress.PHP.YodaConditions.NotYoda"/>
</rule>

Run it

I tested the ruleset on a small plugin file with the usual mistakes in it:

PHP
<?php
/**
 * Plugin Name: My Plugin
 *
 * @package MyPlugin
 */

/**
 * Print a greeting in the footer.
 */
function show_greeting() {
    $name = $_GET['name'];
    if ($name == 'admin') {
        echo '<p>' . __( 'Hello', 'other-domain' ) . ' ' . $name . '</p>';
    }
}
add_action('wp_footer', 'show_greeting');

Run PHPCS from the plugin folder:

Shell
vendor/bin/phpcs

It found 16 errors and 2 warnings in those 17 lines. The full report lists each one with its line number and sniff code. The summary report, with --report=summary, looked like this:

Code
PHP CODE SNIFFER REPORT SUMMARY
----------------------------------------------------------------------
FILE                                                  ERRORS  WARNINGS
----------------------------------------------------------------------
my-plugin.php                                         16      2
----------------------------------------------------------------------
A TOTAL OF 16 ERRORS AND 2 WARNINGS WERE FOUND IN 1 FILE
----------------------------------------------------------------------
PHPCBF CAN FIX 9 OF THESE SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

Then let phpcbf fix what it can:

Shell
vendor/bin/phpcbf

It fixed 8 problems: spaces to tabs, and the spacing inside parentheses. The next phpcs run still had 8 errors and 2 warnings, and every one of them was the kind I flag in plugin review:

  • Unescaped output (WordPress.Security.EscapeOutput.OutputNotEscaped).
  • $_GET['name'] not checked, unslashed or sanitized (WordPress.Security.ValidatedSanitizedInput).
  • No nonce check on form data (WordPress.Security.NonceVerification.Recommended).
  • The wrong text domain (WordPress.WP.I18n.TextDomainMismatch).
  • The missing prefix (WordPress.NamingConventions.PrefixAllGlobals).

That’s the line to remember. phpcbf fixes how the code looks. It never fixes what the code does, so the security errors are always yours. This version passes with no errors:

PHP
<?php
/**
 * Plugin Name: My Plugin
 *
 * @package MyPlugin
 */

/**
 * Print a greeting in the footer.
 */
function my_plugin_show_greeting() {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only display, no state change.
	$name = isset( $_GET['name'] ) ? sanitize_text_field( wp_unslash( $_GET['name'] ) ) : '';

	if ( 'admin' === $name ) {
		echo '<p>' . esc_html__( 'Hello', 'my-plugin' ) . ' ' . esc_html( $name ) . '</p>';
	}
}
add_action( 'wp_footer', 'my_plugin_show_greeting' );

The phpcs:ignore line is there on purpose. Reading a value only to display it doesn’t need a nonce, and the comment after -- says why. Ignore a sniff only when you can write that reason down.

Add Composer scripts

So nobody has to remember the paths, I add two scripts to composer.json:

Shell
composer config scripts.lint "phpcs"
composer config scripts.lint:fix "phpcbf"

Now composer lint checks the project and composer lint:fix cleans up the spacing. Composer puts vendor/bin on the path for its scripts, so the short names work.

Run it on every push

If the plugin is on GitHub, a small GitHub Actions file runs the same check on every push and pull request. I use it as one CI gate for every pull request. Save this as .github/workflows/phpcs.yml:

YAML
name: PHPCS

on: [push, pull_request]

jobs:
  phpcs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7

      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.3'
          tools: composer

      - name: Install dependencies
        run: composer install --no-progress --no-interaction

      - name: Run PHPCS
        run: vendor/bin/phpcs

It installs from your composer.lock, so CI runs the exact PHPCS and WPCS versions you run locally. A non-zero exit code from phpcs fails the job.

In VS Code, I use the PHP Sniffer & Beautifier extension, so the same errors show up in the editor before I commit.

PHPCS checks style and the WordPress security rules. It doesn’t know whether a function exists or what type a value is. For that I pair it with PHPStan for WordPress and WooCommerce. And if you’re getting a plugin ready for the directory, what else WordPress.org checks before approval starts with the name.

Did this answer your question?

If not, tell me what you were looking for. Your question might be my next post.

What were you looking for?

Shameem Reza

Shameem Reza Happiness Engineer at Automattic

I fix WooCommerce problems for a living and review plugins for WordPress.org. Every fix here is tested on a clean site first.

No comments yet. Ask the first question.

No account needed. Comments appear after a quick check.