DEV Community

Cover image for WordPress Coding Standards: Complete Setup Guide for Mac & Windows
Kushang Tailor
Kushang Tailor

Posted on

WordPress Coding Standards: Complete Setup Guide for Mac & Windows

πŸš€ 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)"
Enter fullscreen mode Exit fullscreen mode

Then install Composer:

brew install composer
Enter fullscreen mode Exit fullscreen mode

Verify installation:

composer --version
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Then verify:

composer --version
Enter fullscreen mode Exit fullscreen mode

βœ… 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
Enter fullscreen mode Exit fullscreen mode

Verify installation:

composer --version
Enter fullscreen mode Exit fullscreen mode

Option 2: Using Windows Installer

  1. Download the Windows Installer from getcomposer.org
  2. Run the .exe file
  3. Follow the installation wizardβ€”it will auto-detect PHP installation
  4. Open Command Prompt and verify: composer --version

Option 3: Manual Setup

  1. Download composer.phar from getcomposer.org
  2. Place it in a directory (e.g., C:\composer)
  3. Add this directory to your system PATH
  4. 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
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize Composer

composer init
Enter fullscreen mode Exit fullscreen mode

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:*
Enter fullscreen mode Exit fullscreen mode

Step 4: Register WordPress Standards

./vendor/bin/phpcs --config-set installed_paths vendor/wp-coding-standards/wpcs,vendor/phpcompatibility/php-compatibility
Enter fullscreen mode Exit fullscreen mode

Step 5: Verify Installation

./vendor/bin/phpcs -i
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize Composer

composer init
Enter fullscreen mode Exit fullscreen mode

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:*
Enter fullscreen mode Exit fullscreen mode

Step 4: Register WordPress Standards

.\vendor\bin\phpcs.bat --config-set installed_paths vendor/wp-coding-standards/wpcs,vendor/phpcompatibility/php-compatibility
Enter fullscreen mode Exit fullscreen mode

Step 5: Verify Installation

.\vendor\bin\phpcs.bat -i
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ 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
Enter fullscreen mode Exit fullscreen mode

Scan specific file:

./vendor/bin/phpcs /path/to/file.php
Enter fullscreen mode Exit fullscreen mode

Generate detailed report:

./vendor/bin/phpcs --report=full --report-file=report.txt
Enter fullscreen mode Exit fullscreen mode

Auto-fix issues (when possible):

./vendor/bin/phpcbf
Enter fullscreen mode Exit fullscreen mode

Windows Commands

Basic scan:

.\vendor\bin\phpcs.bat
Enter fullscreen mode Exit fullscreen mode

Scan specific file:

.\vendor\bin\phpcs.bat C:\path\to\file.php
Enter fullscreen mode Exit fullscreen mode

Generate detailed report:

.\vendor\bin\phpcs.bat --report=full --report-file=report.txt
Enter fullscreen mode Exit fullscreen mode

Auto-fix issues:

.\vendor\bin\phpcbf.bat
Enter fullscreen mode Exit fullscreen mode

🎯 Example Output

When you run phpcs, you'll see output like:

FILE: /path/to/plugin.php
 3 | ERROR   | Missing file header comment
Enter fullscreen mode Exit fullscreen mode

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)

  1. Install the "PHPCS for WordPress" extension by Shama
  2. Open VS Code settings (⌘, on Mac or Ctrl+, on Windows)
  3. Search for "phpcs" and configure:
"phpcs.enable": true,
"phpcs.standard": "WordPress",
"phpcs.executablePath": "./vendor/bin/phpcs"
Enter fullscreen mode Exit fullscreen mode

Save and reload. Now you'll see errors highlighted in red as you type!

⚠️ Important: Update the phpcs.executablePath to 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'] );
}
Enter fullscreen mode Exit fullscreen mode

βœ… 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'] ) ) );
}
Enter fullscreen mode Exit fullscreen mode

2. Improper Sanitization (Security)

❌ WRONG - No sanitization

$value = $_GET['search'];
echo $value;
Enter fullscreen mode Exit fullscreen mode

βœ… CORRECT - Properly sanitized and escaped

$search = isset( $_GET['search'] ) ? sanitize_text_field( wp_unslash( $_GET['search'] ) ) : '';
echo esc_html( $search );
Enter fullscreen mode Exit fullscreen mode

3. Function Prefixes (Namespace)

❌ WRONG - Generic function name

function save_settings() {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

βœ… CORRECT - Unique prefix to avoid conflicts

function my_plugin_save_settings() {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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' );
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

For Windows:

.\vendor\bin\phpcs.bat --config-set installed_paths vendor/wp-coding-standards/wpcs,vendor/phpcompatibility/php-compatibility
Enter fullscreen mode Exit fullscreen mode

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 -j flag for parallel processing (if available) macOS example:
./vendor/bin/phpcs --ignore=node_modules,vendor src/
Enter fullscreen mode Exit fullscreen mode

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'];
Enter fullscreen mode Exit fullscreen mode

Or ignore an entire block:

// phpcs:disable WordPress.Security.NonceVerification.Missing
// Your code here
// phpcs:enable WordPress.Security.NonceVerification.Missing
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Or scan staged files:

git diff --cached --name-only | grep '\.php$' | xargs ./vendor/bin/phpcs
Enter fullscreen mode Exit fullscreen mode

Q: PHPCS extension isn't showing errors in VS Code even though phpcs command finds them?

A: Try these solutions:

  1. Reload VS Code window (Command Palette β†’ Reload Window)
  2. Check VS Code settings: Ensure phpcs.enable is true and path is correct
  3. Open terminal in VS Code and verify: ./vendor/bin/phpcs --version
  4. Reinstall the PHPCS extension
  5. 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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.org for 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)