π Introduction: Why WordPress Coding Standards Matter
If you're building WordPress plugins or themes, you've probably heard about WordPress coding standards. But what exactly are they, and why should you care?
Think of coding standards as the style guide for codeβsimilar to how newspapers follow AP style to ensure consistency. WordPress coding standards help ensure that:
- Code is readable across your entire project
- Multiple developers can collaborate without conflicts
- Your code is secure and follows best practices
- WordPress reviewers can approve your code faster
π‘ Pro Tip: Whether you're a seasoned developer or just starting out, implementing coding standards from day one saves hours of refactoring later.
What Are WordPress Coding Standards?
WordPress coding standards consist of five main pillars:
| Standard | Description |
|---|---|
| π PHP Standards | Code formatting, naming conventions, and structure |
| π¨ CSS Standards | Styling conventions and organization |
| βοΈ JavaScript Standards | Script formatting and best practices |
| π‘οΈ Security Standards | Escaping, sanitizing, and validating |
| β Best Practices | Overall code quality and maintainability |
The most important? PHP Standardsβthis is what we'll focus on today, along with the security practices that make WordPress code production-ready.
Step 1: Install Composer (For Both Mac & Windows)
Before we can use WordPress coding standards tools, we need ComposerβPHP's dependency manager. It's essential for managing the PHP CodeSniffer and WordPress-specific linting tools.
π macOS Setup
Option 1: Using Homebrew (Recommended)
If you don't have Homebrew installed, first run:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Then install Composer:
brew install composer
Verify installation:
composer --version
Option 2: Manual Installation
Open Terminal and run:
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer
Then verify:
composer --version
β Success! You should see the composer version number. Now move to Step 2.
Windows Setup
Option 1: Using Chocolatey (Recommended)
If you have Chocolatey installed, simply run in PowerShell (as Administrator):
choco install composer
Verify installation:
composer --version
Option 2: Using Windows Installer
- Download the Windows Installer from
getcomposer.org - Run the
.exefile - Follow the installation wizardβit will auto-detect PHP installation
- Open Command Prompt and verify:
composer --version
Option 3: Manual Setup
- Download
composer.pharfrom getcomposer.org - Place it in a directory (e.g.,
C:\composer) - Add this directory to your system PATH
- Restart Command Prompt and verify installation > β οΈ Note: Windows users should use PowerShell instead of CMD for best results. Right-click and select "Run as Administrator."
Step 2: Set Up WordPress Coding Standards (PHPCS + WPCS)
Now we'll install the tools that actually check your code against WordPress standards.
What We're Installing:
- PHP CodeSniffer (PHPCS) β The core tool that analyzes code
- WordPress Coding Standards (WPCS) β WordPress-specific rules for PHPCS
- PHP Compatibility Checker β Ensures your code works across PHP versions ### π macOS Setup
Step 1: Create a Project Directory
mkdir -p ~/wordpress-project
cd ~/wordpress-project
Step 2: Initialize Composer
composer init
Answer the prompts or press Enter to accept defaults.
Step 3: Install PHPCS and WPCS
composer require --dev squizlabs/php_codesniffer:* wp-coding-standards/wpcs:* phpcompatibility/php-compatibility:*
Step 4: Register WordPress Standards
./vendor/bin/phpcs --config-set installed_paths vendor/wp-coding-standards/wpcs,vendor/phpcompatibility/php-compatibility
Step 5: Verify Installation
./vendor/bin/phpcs -i
You should see a list of installed standards including "WordPress", "WordPress-Core", etc.
β Perfect! Your macOS development environment is ready. You can now scan files for WordPress coding standard violations.
Windows Setup
Step 1: Create a Project Directory
Open PowerShell (as Administrator):
mkdir C:\wordpress-project
cd C:\wordpress-project
Step 2: Initialize Composer
composer init
Answer the prompts or press Enter to accept defaults.
Step 3: Install PHPCS and WPCS
composer require --dev squizlabs/php_codesniffer:* wp-coding-standards/wpcs:* phpcompatibility/php-compatibility:*
Step 4: Register WordPress Standards
.\vendor\bin\phpcs.bat --config-set installed_paths vendor/wp-coding-standards/wpcs,vendor/phpcompatibility/php-compatibility
Step 5: Verify Installation
.\vendor\bin\phpcs.bat -i
You should see a list of installed standards.
β Excellent! Windows setup is complete. You're ready to scan WordPress code.
Step 3: Create Your First Configuration File
PHPCS is now installed, but we need to tell it which standards to use and which files to scan. We do this with a phpcs.xml file.
Create phpcs.xml in your project root:
<?xml version="1.0"?>
<ruleset name="WordPress Project">
<!-- Check all PHP files in src/ -->
<file>src</file>
<file>includes</file>
<!-- Exclude these directories -->
<exclude-pattern>node_modules</exclude-pattern>
<exclude-pattern>vendor</exclude-pattern>
<exclude-pattern>tests</exclude-pattern>
<!-- Use WordPress coding standard -->
<rule ref="WordPress">
<!-- Adjust this rule if you prefer different spacing -->
<exclude name="WordPress.Arrays.ArrayKeySpaced.SpacedAssociativeArray" />
</rule>
<!-- Add PHP 7.2+ compatibility check -->
<rule ref="PHPCompatibility">
<config name="testVersion" value="7.2-" />
</rule>
</ruleset>
π‘ Tip: You can customize which rules to enforce. This configuration checks WordPress standards while excluding certain non-critical rules that might be too strict for your project.
Step 4: Running Your First Code Scan
Now for the exciting partβlet's scan some actual code!
π macOS Commands
Basic scan:
./vendor/bin/phpcs
Scan specific file:
./vendor/bin/phpcs /path/to/file.php
Generate detailed report:
./vendor/bin/phpcs --report=full --report-file=report.txt
Auto-fix issues (when possible):
./vendor/bin/phpcbf
Windows Commands
Basic scan:
.\vendor\bin\phpcs.bat
Scan specific file:
.\vendor\bin\phpcs.bat C:\path\to\file.php
Generate detailed report:
.\vendor\bin\phpcs.bat --report=full --report-file=report.txt
Auto-fix issues:
.\vendor\bin\phpcbf.bat
π― Example Output
When you run phpcs, you'll see output like:
FILE: /path/to/plugin.php
3 | ERROR | Missing file header comment
This tells you exactly where problems are and what to fix!
Step 5: Integrating with Code Editors
Scanning manually is helpful, but catching errors while you code is even better.
VS Code Integration (Recommended)
- Install the "PHPCS for WordPress" extension by Shama
- Open VS Code settings (β, on Mac or Ctrl+, on Windows)
- Search for "phpcs" and configure:
"phpcs.enable": true,
"phpcs.standard": "WordPress",
"phpcs.executablePath": "./vendor/bin/phpcs"
Save and reload. Now you'll see errors highlighted in red as you type!
β οΈ Important: Update the
phpcs.executablePathto match your setup. Windows users should use.\vendor\bin\phpcs.bat.
Understanding Common WordPress Code Standards Violations
Let's decode some common errors you'll encounter:
1. Missing Nonces (Security)
β WRONG - No security verification
if ( isset( $_POST['save'] ) ) {
update_option( 'my_option', $_POST['value'] );
}
β
CORRECT - Verified nonce
if ( isset( $_POST['save'], $_POST['nonce'] ) &&
wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'my_action' ) ) {
update_option( 'my_option', sanitize_text_field( wp_unslash( $_POST['value'] ) ) );
}
2. Improper Sanitization (Security)
β WRONG - No sanitization
$value = $_GET['search'];
echo $value;
β
CORRECT - Properly sanitized and escaped
$search = isset( $_GET['search'] ) ? sanitize_text_field( wp_unslash( $_GET['search'] ) ) : '';
echo esc_html( $search );
3. Function Prefixes (Namespace)
β WRONG - Generic function name
function save_settings() {
// ...
}
β
CORRECT - Unique prefix to avoid conflicts
function my_plugin_save_settings() {
// ...
}
Creating a Plugin Template Following Standards
Let's build a proper WordPress plugin structure from scratch:
my-awesome-plugin/
βββ my-awesome-plugin.php # Main plugin file
βββ includes/
β βββ class-plugin.php # Main plugin class
β βββ class-settings.php # Settings handler
βββ assets/
β βββ css/
β β βββ style.css
β βββ js/
β βββ script.js
βββ languages/
β βββ my-awesome-plugin.pot # Translations
βββ vendor/ # Composer dependencies
βββ composer.json
βββ phpcs.xml
βββ README.md
Main plugin file (my-awesome-plugin.php):
<?php
/**
* Plugin Name: My Awesome Plugin
* Plugin URI: https://example.com
* Description: An awesome plugin following WordPress standards
* Version: 1.0.0
* Author: Your Name
* License: GPL-2.0-or-later
* Text Domain: my-awesome-plugin
* Domain Path: /languages
*
* @package MyAwesomePlugin
*/
// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Include autoloader.
require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
/**
* Initialize the plugin.
*
* @return void
*/
function my_awesome_plugin_init() {
do_action( 'my_awesome_plugin_init' );
}
add_action( 'plugins_loaded', 'my_awesome_plugin_init' );
Best Practices Checklist
| Practice | Description |
|---|---|
| β Always validate input | Use sanitize_* and validate_* functions for all user input |
| β Escape output | Use esc_html, esc_attr, esc_url before outputting data |
| β Use nonces | Protect form submissions with WordPress nonce verification |
| β Name spacing | Prefix all functions, hooks, and classes uniquely |
| β Document code | Use PHPDoc comments on all functions and classes |
| β Use proper hooks | Leverage WordPress actions and filters for extensibility |
Troubleshooting Common Issues
Q: PHPCS says "could not find any installable packages"?
A: Make sure you have PHP and Composer installed. Run php --version to verify. Also ensure Composer is in your system PATH. On Windows, restart Command Prompt or PowerShell after installing Composer.
Q: Auto-fix (phpcbf) isn't working?
A: Some violations can't be auto-fixed. Check the error message for details. Complex issues like security concerns (nonces, sanitization) require manual fixing. Run phpcbf with the --standard=WordPress flag to apply only WordPress rules.
Q: How do I exclude specific files?
A: Edit phpcs.xml and add <exclude-pattern> tags. Example:
<exclude-pattern>node_modules</exclude-pattern>
<exclude-pattern>vendor</exclude-pattern>
<exclude-pattern>*/tests/*</exclude-pattern>
Q: I'm getting "WordPress standard could not be found" error?
A: This means WordPress Coding Standards (WPCS) isn't registered. Run this command to fix it:
For macOS:
./vendor/bin/phpcs --config-set installed_paths vendor/wp-coding-standards/wpcs,vendor/phpcompatibility/php-compatibility
For Windows:
.\vendor\bin\phpcs.bat --config-set installed_paths vendor/wp-coding-standards/wpcs,vendor/phpcompatibility/php-compatibility
Then verify: phpcs -i or phpcs.bat -i
Q: Why is PHPCS taking so long to scan my project?
A: Scanning large projects can take time. To speed it up:
- Exclude unnecessary directories in
phpcs.xml(node_modules, vendor, etc.) - Run phpcs on specific files instead of the whole project
- Use the
-jflag for parallel processing (if available) macOS example:
./vendor/bin/phpcs --ignore=node_modules,vendor src/
Q: How do I ignore a specific line that I know violates standards?
A: Use the PHPCS annotation comment before the problematic line:
// phpcs:ignore WordPress.Security.NonceVerification.Missing
$unsafe_value = $_POST['value'];
Or ignore an entire block:
// phpcs:disable WordPress.Security.NonceVerification.Missing
// Your code here
// phpcs:enable WordPress.Security.NonceVerification.Missing
Q: I'm getting different results than a team member. Why?
A: Version mismatches! Make sure both of you are using the same versions of PHPCS and WPCS. Commit your composer.lock file to version control:
git add composer.lock
git commit -m "Lock composer dependencies"
Q: How do I run PHPCS on only modified files (useful for Git)?
A: Get list of changed files and scan them:
macOS/Linux:
git diff --name-only HEAD | grep '\.php$' | xargs ./vendor/bin/phpcs
Or scan staged files:
git diff --cached --name-only | grep '\.php$' | xargs ./vendor/bin/phpcs
Q: PHPCS extension isn't showing errors in VS Code even though phpcs command finds them?
A: Try these solutions:
- Reload VS Code window (Command Palette β Reload Window)
- Check VS Code settings: Ensure
phpcs.enableistrueand path is correct - Open terminal in VS Code and verify:
./vendor/bin/phpcs --version - Reinstall the PHPCS extension
- Check VS Code output panel (View β Output) for error messages
Q: Can I create custom coding standards for my project?
A: Yes! Create a custom ruleset in phpcs.xml that extends WordPress standard:
<?xml version="1.0"?>
<ruleset name="My Custom Standard">
<description>Custom standards based on WordPress</description>
<!-- Inherit WordPress standard -->
<rule ref="WordPress" />
<!-- Override or add custom rules -->
<rule ref="WordPress.NamingConventions.PrefixAllGlobals">
<properties>
<property name="prefixes" type="array">
<element value="my_plugin" />
<element value="my_custom" />
</property>
</properties>
</rule>
</ruleset>
Q: My plugin passed phpcs but failed WordPress.org submission. What's wrong?
A: PHPCS catches most issues, but not everything. WordPress reviewers also check:
- Security: Proper use of nonces, escaping, sanitization
- Documentation: Clear comments and proper PHPDoc
- Functionality: Plugin works correctly and doesn't conflict
- Performance: No unnecessary database queries or API calls
- Best practices: Proper use of WordPress hooks and functions Review WordPress.org plugin handbook before submission. Consider having someone else review your code first.
Q: How often should I update PHPCS and WPCS?
A: Update when new versions are released (especially for security fixes). Update your composer packages:
composer update squizlabs/php_codesniffer wp-coding-standards/wpcs
Always test your code after updating to catch any new violations introduced by rule changes.
Next Steps: Advanced Setup
- π Git Hooks: Auto-run phpcs on commit with husky
- π CI/CD: Add phpcs checks to GitHub Actions
- π― Custom Rules: Create project-specific coding rules
- π Team Standards: Share phpcs.xml with your team
π Learn More: Visit
developer.wordpress.orgfor the complete WordPress coding standards documentation.
Conclusion
You now have a complete WordPress development environment set up with coding standards checking! Whether you're building plugins, themes, or contributing to WordPress itself, these tools will help you write cleaner, more secure code.
The key takeaway? Consistency matters. By following these standards from day one, you'll save time on code reviews, reduce bugs, and make your WordPress projects more maintainable.
Happy coding! π
Share This Guide
Found this helpful? Share it with your developer friends and don't forget to drop a comment if you have questions or want to discuss WordPress coding standards further!
Top comments (0)