WordPress Coding Standards
WordPress Coding Standards (WPCS)
The WordPress Coding Standards (WPCS) are the official coding standards guide for WordPress core development. There are several standards by technology / topic:
- Accessibility Coding Standards
- CSS Coding Standards
- HTML Coding Standards
- JavaScript Coding Standards
- PHP Coding Standards
- Inline Documentation Standards
- JavaScript Documentation Standards
- PHP Documentation Standards
PHP Standards Recommendations (PSR)
The PHP Standards Recommendations are the collection of standards used by the worldwide PHP community, and drafted by the PHP Framework Interop Group (PHP-FIG).
WPCS vs PSR
The WordPress coding standards are slightly different from those of from the general PHP community, which uses the PSRs.
One instance of divergence is on the basic coding formatting (indenting, casing for class names and functions, properties, methods, etc). WPCS diverges from the PSR-1 (Basic Coding Standard) and the PSR-12 (Extended Coding Style).
If you are working on a theme or plugin that will be submitted to the WordPress official directory, you will need to follow the WordPress coding standards. For custom plugins, it may be advantageous to follow the PSRs more closely.
CoLab reccomended standards
The specific coding standards reccomended for WordPress development would include:
- WordPress Coding Standards
- PHP Standards Recommendations:
- PSR-1: Basic Coding Standard - standard coding elements that are required to ensure a high level of technical interoperability between shared PHP code.
- PSR-12: Extended Coding Style - extends the basic standards, and enumerates a shared set of rules and expectations about how to format PHP code.
- PSR-4: Autoloader - standard for autoloading of classes from file paths.
- PSR-5: PHPDoc - standard for code documentation using inline comments. Also related is PSR-19: PHPDoc tags for the individual tags used for PHPDoc formatted comments.
Implementing coding standards
To help implement the WordPress coding standards in your development, there are various tools you can use.
PHP_CodeSniffer (PHPCS) is a set of two PHP scripts; the main phpcs
script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf
script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.
If using Composer for dependecy management (you really should), then you can add PHPCS to your dev dependencies:
composer require --dev squizlabs/php_codesniffer
PHPCS can be used via the CLI, or integrated with code editors, IDEs or build tooling. You can also set up pre-comit hooks in git to enforce coding standards.
Resources
- Article: Set Up PHP CodeSniffer for Local Development
- Guide: How to set up commit hooks for PHP
- Tutorial: What is a DocBlock? - phpDocumentor documentation.