To set up you WordPress project locally to work with solid checks for coding standards there are several ways to do it. You could do checks on the repository post push or merge, you could do it in your workspace project with PHP Code Sniffer and finally you do the package setup globally. If you use VS Code you can then also add the Sniffer and Beautifier extension to work with the package. We followed a setup on our PC installing the package globally.

Global Installation PHP Code Sniffer

Global installation of the PHP Code Sniffer by Squizlabs is done like any other PHP Composer package. So this command should do the trick with composer installed :

composer global require "squizlabs/php_codesniffer=*"

WordPress Coding Standards Repo

We chose to Clone of the WordPress code standard repository to our code directory. We can clone from Github repository and so always update the package later on. Following command used:

cd code/
git clone git@github.com:WordPress-Coding-Standards/WordPress-Coding-Standards.git pcs

Then we need to make sure PHP CS can load these new standards. Run this phpcs command for just that:

phpcs --config-set installed_paths ~/code/wpcs

Double check the new standards are are added:

phpcs -i
The installed coding standards are MySource, PEAR, PSR1, PSR2, PSR12, Squiz, Zend, WordPress, WordPress-Core, WordPress-Docs and WordPress-Extra

As you can see they were.

VS Studio Code Extension

The installation of the actual VS Studio Code extension PHP Sniffer and Beautifier .

And the proper settings.json so Visual Studio Code loads the code sniffer and WordPress coding standards properly:

{
    "[php]": {
        "editor.defaultFormatter": "valeryanm.vscode-phpsab",
        "editor.formatOnSave": true
    },
    "phpsab.executablePathCBF": "/Users/user/.composer/vendor/squizlabs/php_codesniffer/bin/phpcbf",
    "phpsab.executablePathCS": "/Users/user/.composer/vendor/squizlabs/php_codesniffer/bin/phpcs",
    "phpsab.standard": "WordPress",
    "phpsab.snifferArguments": [
        "--ignore=*/wp-admin/*,*/wp-includes/*"
    ]
}

Custom Ruleset

And last but not least the `phpcs.xml.dist` with your own custom rules:

<?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="ALWTU" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/PHPCSStandards/PHP_CodeSniffer/master/phpcs.xsd">
    <description>My custom coding standard.</description>
    <rule ref="PSR2">
        <exclude name="PSR1.Methods.CamelCapsMethodName"/>
    </rule>
</ruleset>

in our case we do want to allow camel case so we turned off the CameCaps Method. You can of course add other rules.

Leave a Reply

Your email address will not be published. Required fields are marked *