This tutorial will guide you from installing PHP_CodeSniffer in your terminal and IDE to solving the most common WordPress coding standard violations.

Set Up PHP CodeSniffer and the WordPress Coding Standard in Your System

To install PHP CodeSniffer, I’m going to use Composer. If you still need to install Composer in your system, see the instructions here.

The first step is to install the main PHP_CodeSniffer package documented in this GitHub repository.

composer global require "squizlabs/php_codesniffer=*"

This other command is used to perform a global installation of the coding standards provided by WordPress.

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

Note that to use the PHP CodeSniffer scripts in any folder, you need to add the Composer folder to the PATH environment variable of your system. To do that, first, get the path to the Composer folder by running this command:

composer config --list --global 

The path will be available in the “home” line of the returned output. To add a new environment variable on macOS (tested with macOS Sonoma), edit the following files in your user main user folder (E.g. “/Users/yourusername/” ):

.bash_profile
.zprofile

And add this line:

export PATH=/Users/danilo/.composer/vendor/bin:$PATH

Select a Coding Standard

The WordPress coding standard package comes with these rulesets:

  • WordPress
  • WordPress-Core
  • WordPress-Docs
  • WordPress-Extra

In the rest of the tutorial, we will use the WordPress ruleset to use all the sniffs available in the project. For more information, see the coding standards here.

We can list the installed standards with the following command:

phpcs -i

Set the default coding standard to “WordPress”:

 phpcs --config-set default_standard WordPress

You can optionally customize the coding standard by defining a custom ruleset. This can be done by adding a custom ruleset.xml file in the main folder of the project.

For more information on the available rulesets, see the Annotated Ruleset page.

The following ruleset.xml file does what follows:

  1. It sets the rule used to check the code to “WordPress”
  2. It excludes two folders commonly used to store files from external libraries. Specifically, it excludes the node_module folder, which holds the npm libraries, and the vendor folder to skip the PHP libraries installed with Composer.
<?xml version="1.0"?>
<ruleset name="WordPress Coding Standards">
    <description>PHP_CodeSniffer ruleset.</description>

    <!-- Rules -->
    <rule ref="WordPress" />

    <!-- Exclude paths -->
    <exclude-pattern>*/node_modules/*</exclude-pattern>
    <exclude-pattern>*/vendor/*</exclude-pattern>

</ruleset>

How to Fix the Most Common WordPress Coding Standard Violations

This section includes common violations of the WordPress Standards and solutions to solve these issues.

Security

WordPress.Security.NonceVerification.Recommended:

This validation error is presented when data, usually sent with a form, are processed without verifying a nonce. It’s worth noting that not using a nonce exposes the site to CSRF attacks.

You can remove this violation by adding a nonce in the page that sends the data, for example, with wp_nonce_field() and by checking the nonce value with wp_verify_nonce() or check_admin_referer() before processing the page.

In this example, data are processed without checking the nonce, and a violation is generated:

if ( $form_submitted ) {

    // Sanitization.
    $foo = isset( $_POST['foo'] ) ? sanitize_text_field( wp_unslash( $_POST['foo'] ) ) : null;

    // Additional data processing ...

Here, a nonce named foo_nonce registered with the action name foo is verified with check_admin_referer(). If the provided nonce value is invalid, this function exits the script.

if ( $form_submitted ) {

    // Nonce verification.
    check_admin_referer( 'foo', 'foo_nonce' );

    // Sanitization.
    $foo = isset( $_POST['foo'] ) ? sanitize_text_field( wp_unslash( $_POST['foo'] ) ) : null;

    // Additional data processing ...

WordPress.Security.ValidatedSanitizedInput.MissingUnslash

This violation is generated when superglobal variables are not unslashed before sanitization.

$foo = isset( $_POST['foo'] ) ? sanitize_text_field( $_POST['foo'] ) : null;

To solve use wp_unslash():

$foo = isset( $_POST['foo'] ) ? sanitize_text_field( wp_unslash( $_POST['foo'] ) ) : null;

Database

WordPress.DB.PreparedSQL.InterpolatedNotPrepared

The wpdb::prepare() method should always be used to sanitize variables used in a SQL statement.

The following example generates a violation:

$sql = "DELETE FROM foo_table WHERE id = $delete_id";

This is fixed with:

$safe_sql = $wpdb->prepare( "DELETE FROM foo_table WHERE id = %d ", $delete_id );

Operators

Squiz.Operators.ValidLogicalOperators.NotAllowed

The and operator is not allowed:

if ( $foo and $bar ){
    //Do something.
}

Simply replace it with the && operator:

if ( $foo && $bar ){
    //Do something.
}

Squiz.Operators.ValidLogicalOperators.NotAllowed

The WordPress Coding Standard doesn’t allow the or operator:

if ( $foo or $bar ){
    //Do something.
}

To solve it, simply replace it with ||:

if ( $foo || $bar ){
    //Do something.
}

Universal.Arrays.DisallowShortArraySyntax.Found

Arrays can’t be declared with this short syntax:

$foo = [];

To solve, use the standard syntax:

$foo = array();

Commenting

Squiz.Commenting.InlineComment.NoSpaceBefore

This validation error is triggered when no space is found before standard comments.

//My comment.

To solve, add a space before the comments:

// My comment.

Squiz.Commenting.InlineComment.InvalidEndChar

Inline comments should always end with a full-stop, an exclamation mark, or a question mark. Comments that end with any other character trigger this violation.

Example of a comment that triggers the violation:

// My comment

The same comment with the error fixed.

// My comment.

PHP

WordPress.PHP.YodaConditions.NotYoda

This happens when an if statement uses a variable as the first operand. Solve this violation to avoid accidental assignments when a comparison is intended.

The following comparison generates the violation:

if ( $foo === 10 ) {
    // Do something.
}

To solve, invert the operands. In this way, an accidental assignment becomes impossible.

if ( 10 === $foo ) {
    // Do something.
}

Detect WordPress Coding Standard Violations With the Terminal

With the phpcs command you can check a file and return an output with the violations:

phpcs example.com

Note that you can also check folders. However, before validating the main folder of a plugin or a theme, it is recommended to exclude library files with a custom ruleset.xml file, as explained in a previous section of this tutorial.

phpcs myfolder/

Check a single file with a specific standard. Here, the “WordPress” ruleset is used to detect the violations on the example.php file.

phpcs example.php --standard=WordPress

To list all the phpcs options, use this command:

phpcs -h

Automatically Fix WordPress Coding Standard Violations

The script provided by PHP_CodeSniffer to fix violations is phpcbf.

It’s important to note this command only solves part of the violations. Problems that require a complex resolution should be manually fixed.

Examples of complex violations that can’t be solved automatically are:

  • Missing nonce
  • Sanitisation problems

These are examples of simple violations that can be solved automatically.

  • Spacing problems
  • Spaces used instead of tabs

To fix violations, simply enter phpcbf followed by the considered file or folder:

phpcbf example.php

To customize the behavior of phpcbf use the available options. You can list the options with:

phpcbf -h

Set Up PHP CodeSniffer With the WordPress Coding Standard in PHPStorm

Let’s see how to configure this IDE to validate the WordPress Coding Standard using PHP CodeSniffer.

Step 1: Configuration in the Quality Tools

The first step in the process is to configure the location of the PHP CodeSniffer script. We can do this with the following procedure:

  1. Open the PHPStorm settings
  2. Select the PHP -> Quality Tools menu
  3. Enter in the PHP_CodeSniffer section
  4. In the Configuration field select “System PHP” and enter the path to the phpcs and phpcbf scripts
PHP_CodeSniffer has been configured in the PHP -> Quality Tools settings page of PHPStorm.
PHP_CodeSniffer has been configured in the PHP -> Quality Tools settings page of PHPStorm.

In this menu, you can also set the file extensions checked by PHP CodeSniffer.

I also recommend you to enable the Show sniff name checkbox. With this option activated, the phpcs: prefix will be added to all the PHP_CodeSniffer violations. So you can distinguish the PHP CodeSniffer problems from the other problems detected by the IDE.

With the Coding Standard option, you can select between existing coding standards like “WordPress” or “WordPress-Core” or also customize a coding standard. To customize a coding standard, select “Custom” and then add the path to a custom ruleset file.

Step 2: Configure the Inspections

Go to Editor -> Inspections, then in the quality tools category, enable the “PHP_CodeSniffer” checkbox.

The PHP_CodeSniffer inspection is enabled in PHPStorm.
The PHP_CodeSniffer inspection is now enabled in PHPStorm.

Step 3: Set the Proper Code Style

Proceed to the Editor -> Code Style -> PHP option and then click “Set From …”. Here, load the “WordPress” style.

The "WordPress" coding style has been set in the Editor -> Code Style -> PHP tab of PHPStorm.
The “WordPress” coding style has been set in the Editor -> Code Style -> PHP tab of PHPStorm. By loading this coding style, we instructed the editor to use (among many other settings) the tab character instead of spaces.

Since PHP usually alternates with HTML, proceed to the Code Style -> HTML folder and enable the Use tab character option for this file type.

Step 4: Use the Inspection to Improve Your Code

The inspections should now be available while editing a file. To check the result of the inspection, proceed as follows:

  1. Open a file with a file extension that has been listed in the file extension option previously configured.
  2. Open the Problems tab on the left sidebar of PHPStorm. Here, you will find the PHP CodeSnippets messages.
The "Problems" tab of PHPStorms lists the WordPress coding standards violations.
The Problems tab of PHPStorms lists the WordPress coding standards violations. By double-clicking a specific violation, the editor will move to the line with the violation.

Configure PHP CodeSniffer with VSCode

With VSCode you can install the extension PHP Sniffer.

The extension doesn’t require an initial configuration. Just install it from the File -> Preferences -> Extensions menu, and then verify if it’s working by hovering the mouse over the errors in your PHP file. For each violation, a tooltip with the details is provided.

A description of a violation is visible in the tooltip generated by the PHP Sniffer extension of VSCode.
A description of a violation is visible in the tooltip generated by the PHP Sniffer extension of VSCode.