Coding standards in WordPress development are pivotal for a robust and sustainable codebase. They serve as guidelines and conventions that developers adhere to when writing code, helping enhance collaboration, streamline maintenance, and ensure overall reliability.

Moreover, coding standards safeguard against common pitfalls and errors, improving code quality. In WordPress development, where multiple contributors often collaborate on a single project, coding standards underpin effective teamwork. They facilitate communication, mitigate potential conflicts, and contribute to a more efficient development process.

Adhering to coding standards promotes consistency across projects, making it easier for you to switch between different codebases seamlessly. This consistency extends to code readability and maintainability and fosters a shared understanding among team members.

The official WordPress coding standards cover five key areas for a cohesive and efficient development process:

  • PHP for ensuring server-side code consistency
  • HTML for promoting structured and semantic markup
  • JavaScript for effective client-side functionality
  • CSS for maintaining a consistent styling approach
  • Accessibility for ensuring that the end product is inclusive and user-friendly for individuals with diverse needs

In this article, we explore these coding standards to help you get started on building compliant websites and perhaps contributing to the WordPress development community.

PHP standards in WordPress development

WordPress-specific PHP coding standards ensure consistency and readability in WordPress code. They’re mandatory for WordPress Core and strongly recommended for themes and plugins. These standards cover various aspects, including naming conventions, indentation, and code structure to improve readability and ease collaboration.

WordPress PHP standards span the following categories:

  • General — These standards include placing the opening and closing PHP tags on a line by themselves when embedding a multi-line PHP snippet in an HTML block, avoiding shorthand PHP tags when using single and double quotes, and guidelines for writing include and require statements:
// Opening and closing PHP tags within HTML:
// Put open/close tags on their own lines.

## DO
function foo() {
  ?>
  <div>
    <?php
    echo esc_html (
      bar (
        $param1,
        $param2
      )
    );
    ?>
  </div>
  <?php
}

## DON'T
if ( $x === $y ) { ?>
  <div>
    <!-- HTML content -->
  <?php }
// Avoid shorthand PHP tags

## DO
<?php ... ?>
<?php esc_html( $x ); ?>

## DON'T
<? ... ?>
<? esc_html( $x ); ?>
// Writing include/require statements:
// Avoid include_once as it continues execution 
// even if the file is not found. 
// Do not use brackets around the file path.

## DO
require_once ABSPATH . 'file-name.php'

## DON'T
require_once  __DIR__ . '/file-name.php'
include_once  ( ABSPATH . 'file-name.php' );
  • Naming — Standards for naming include naming conventions and interpolation for naming dynamic hooks:
## DO
// Use lowercase letters for function and variable names.
function my_function( $some_variable ) {}

// Use uppercase letters for constant names.
define('MAX_AGE', 60);

## DON'T
// Use camelCase.
function myFunction( $someVariable ) {}
  • Whitespace — Whitespace standards set guidelines for space usage, indentation, and removing trailing spaces. (If you want to start an enthusiastic debate among developers, just ask if they prefer tabs or spaces for indenting code. Whatever your preference, the official recommendation for WordPress developers is tabs — and that goes for JavaScript and CSS, in addition to PHP. So, keep that in mind when working on collaborative projects.)
## DO
// Put spaces after commas.
$colors = ['red', 'green', 'blue']

// Put spaces on both sides of the opening and 
// closing brackets of control structures. 
foreach( $foo as $bar ) { ...

// Defining a function:
function my_function() { ...

// Logical comparisons:
if ( ! $foo ) { ...

// Accessing array items:
$a = $foo['bar']
$a = $foo[ $bar ]

## DON'T
$colors = ['red','green','blue']
foreach($foo as $bar){ ...
function my_function(){ ...
if (!$foo) { ...
$a = $foo[ ‘bar’ ]
$a = $foo[$bar]
  • Formatting — Formatting standards for WordPress PHP development include brace styles, array declarations, guidelines for multi-line function calls, type declarations, magic constants, and the spread operator:
// DO
// Use the following brace style.
if ( condition ) {
    action();
} elseif ( condition2 ) {
    action2();
} else {
    default_action();
}

// Declare arrays using the long syntax.
$numbers_long = array(1, 2, 3, 4, 5);
/* In multi-line function calls, each parameter should only take up one line.
Multi-line parameter values should be assigned a variable, and the variable passed to the function call. */
$data = array(
    'user_name' => 'John Doe',
    'email'     => '[email protected]',
    'address'   => '123 Main Street, Cityville',
);
$greeting_message = sprintf(
    /* translation function. %s maps to User's name */
    __( 'Hello, %s!', 'yourtextdomain' ),
    $data['user_name']
);
$result = some_function (
    $data,
    $greeting_message,
    /* translation function %s maps to city name*/
    sprintf( __( 'User resides in %s.' ), 'Cityville' )
);

// Magic constants should be uppercase.
// The ::class constant should be lowercase with no spaces around the scope resolution operator (::).
add_action( my_action, array( __CLASS__, my_method ) );
add_action( my_action, array( My_Class::class, my_method ) );

/* Add a space or new line with appropriate
   indentation before a spread operator.

   There should be:

   * No space between the spread operator and the 
     variable/function it applies to.

   * No space between the spread and the reference 
     operators when combined.
*/

//DO
function some_func( &...$arg1 ) {
    bar( ...$arg2 );
    bar(
        array( ...$arg3 ),
        ...array_values( $array_vals )
    );
}

//DONT
function some_func( &   ...  $arg1 ) {
    bar(...
        $arg2 );
    bar(
        array( ...$arg3 ),...array_values( $array_vals )
    );
}
  • Declare statements, namespace, and import statements — These coding standards cover namespace declarations and use statements:
// Each namespace declaration should contain 
// capitalized words separated by underscores.
namespace My_CompanyProjectKinsta_ProjectUtilities;

// Import use statements can use aliases 
// to prevent name collisions.
use Project_NameFeatureClass_C as Aliased_Class_C;
  • Object-oriented programming (OOP) — These standards include using only one object structure per file, providing guidelines for using trait use statements, ensuring visibility is always declared, outlining the order of visibility and modifier, and overviewing rules for object instantiation:
// Trait use statements should be at the top of a class.
// Trait use should have at least one line before and after
// the first and last statements.
// Always declare visibility.
class Foo {
    use Bar_Trait;
    public $baz = true;
    ...
}

// Always use parentheses when instantiating a new 
// object instance.
// Don't add space between a class name and the opening bracket.
$foo = new Foo();
    • Control structures — Control structures include using elseif, not else if, and guidelines for Yoda conditions.Yoda statements: When mixing variables with constants, literals, or function calls in logical comparisons, place the variable on the right to prevent accidental assignment, as shown below:
// A "legal" comparison:
if ( true === $result ) {
    // Do something with $result
}

// But a typo like this could get past you:
if ( $result = true ) {
    // We will always end up here
}
  • Operators — These standards cover ternary operators, the error control operator (@), and increment/decrement operators:
// Always have ternary operators 
// test if the statement is true, not false.
$programming_language = ( 'PHP' === $language ) ? 'cool' : 'meh'; 

// Favor pre-increment/decrement over post-increment/decrement
// for stand-alone statements.

// DO
--$a;

// DON'T
$a--;
  • Database — Database coding standards provide instructions for performing database queries and formatting SQL statements.
  • Additional recommendations — Additional recommendations include standards like using self-explanatory flag values for function arguments, clever code, closures (anonymous functions), regular expressions, shell commands, and instructions to avoid extract().

WordPress inline documentation standards for PHP code

In addition to the guidelines above, WordPress provides inline documentation standards for PHP code. WordPress uses a customized documentation schema that draws inspiration from PHPDoc syntax, an evolving standard for providing documentation to PHP code maintained by phpDocumentor. These standards streamline generating external documentation and contribute to the broader WordPress developer community by fostering a shared understanding of codebase structures.

PHP documentation in WordPress mostly appears as formatted blocks or inline comments. Document the following in WordPress files:

  • Functions and class methods
  • Classes
  • Class members, including properties and constants
  • Requires and includes
  • Hooks (actions and filters)
  • Inline comments
  • File headers
  • Constants

HTML and CSS standards in WordPress

WordPress themes and plugins adhere to strict HTML coding standards to ensure consistency, accessibility, and maintainability. The guidelines emphasize semantic markup, encouraging developers to use HTML elements for their intended purposes. This practice enhances content structure and improves search engine optimization (SEO) performance. Additionally, you’re encouraged to validate your HTML to guarantee compatibility across browsers.

HTML code standards provide guidelines for:

  • Validation—You should validate all your HTML pages against the W3C validator to ensure that your markup is well-formed.
  • Self-closing elements – The forward slash in self-closing elements should have one space preceding it.
<!-- DO -->
<br />

<!-- DON'T –>
<br/>
  • Attributes and tags – All attributes and tags should be in lowercase. Additionally, attribute values should only be lowercase when for machine interpretation. If you are writing for humans, use proper title capitalization.
<!-- DO -->
<a href="http://example.com/" title="Link Description">Descriptive text</a>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<!-- DON'T -->
<a HREF="http://example.com/" TITLE="link description">Click here</a>
  • Quotes – All attributes must have a value and must use single or double quotes. Failing to quote the values can lead to security vulnerabilities.
<!-- DO -->
<input type="text" name="email" disabled="disabled" />
<input type='text' name='email' disabled='disabled' />

<!-- DON'T -->
<input type=text name=email disabled>
  • Indentation – The HTML indentation should always reflect the logical structure. When mixing PHP and HTML, indent the PHP blocks to match the surrounding HTML code.
<!-- DO -->
<?php if ( ! have_articles() ) : ?>
<div class="article">
    <h1 class="article-title">Not Found</h1>
    <div class="article-content">
        <p>No results were found.</p>
        <?php get_error_msg(); ?>
    </div>
</div>
<?php endif; ?>

<!-- DON'T -->
<?php if ( ! have_articles() ) : ?>
<div class="article">
<h1 class="article-title">Not Found</h1>
<div class="article-content">
<p>No results were found.</p>
<?php get_error_msg(); ?>
</div>
</div>
<?php endif; ?>

In addition to these HTML standards, WordPress’ CSS standards help you create clean, modular, and responsive stylesheets. They set a baseline for collaboration and review, from core code to themes to plugins. These guidelines help ensure your code is readable, consistent, and meaningful.

WordPress CSS code standards emphasize using specific classes to target elements, promoting a consistent and organized structure. Specifically, they outline standards for:

  • Structure:
/* DO 
Each selector should be on its own line ending with 
a comma or curly brace. The closing brace should occupy 
the same indentation level as the opening selector. */
#selector-1,
#selector-2 {
    property: value;
}
  • Selectors:
/* DO 
Use lowercase and separate words using hyphens.
Use double quotes around values for attribute selectors.
Avoid overqualified selectors, such as div.container. */
#contact-form {
    property: value;
}
input[type="text"] {
    property: value;
}
  • Properties (ordering and vendor prefixes):
/* Append properties with a colon and a space. 
Properties should be lowercase — except font names 
snd vendor-specific properties — and use shorthand. */
#selector {
    property: value;
}
  • Values:
/* Add a space before the value and a semicolon after.
Use double quotes.
0 values should not have units.
Use a leading zero for decimal values.
Delineate multiple comma-separated values for 
a single property with a space or new line. */
#contact-form {
    font-family: "Helvetica Neue", sans-serif;
    opacity: 0.9;
    box-shadow:
        0 0 0 1px #5b9dd9,
        0 0 2px 1px rgba(20, 120, 170, 0.9);
}
  • Media queries:
/* Rules set for media queries should be indented one level in.
Keep media queries grouped by media at the bottom of the stylesheet. */
@media all and (max-width: 1024px) and (min-width: 780px) {
    $selector {
        property: value;
    }        
}
  • Commenting:

Since its inception in 2003, WordPress coding standards for HTML and CSS have aligned with the World Wide Web Consortium (W3C) guidelines for HTML and CSS. Emphasizing the integration of responsive design principles and semantic markup, W3C standards have influenced the development of themes and plugins, beginning with the release of HTML5 and CSS3.

This adoption of W3C guidelines ensures WordPress websites adhere to global web standards, enhancing interoperability and user experience and reflecting a commitment to staying current, secure, and compatible within the broader web ecosystem.

Adherence to these guidelines in WordPress emphasizes HTML quality verification against the W3C HTML markup validator.

These HTML and CSS standards ensure a visually appealing, user-friendly, and efficient presentation of WordPress websites across platforms. They support a seamless user experience and facilitate collaboration among developers working on diverse aspects of the WordPress ecosystem.

JavaScript coding standards in WordPress

WordPress coding standards also provide guidelines for formatting and styling JavaScript code for themes and plugins. Additionally, these standards help promote code consistency alongside core PHP, HTML, and CSS code.

The WordPress JavaScript coding standards are built on the jQuery JavaScript Style Guide, which emerged in 2012 as a comprehensive set of coding conventions that enhances code consistency and readability. Initially, it catered specifically to jQuery projects, but its success prompted widespread adoption beyond the framework.

While the jQuery guidelines inform WordPress standards, there are some notable differences for WordPress development:

  • WordPress uses single quotation marks for string declarations.
  • Case statements are indented within switch blocks.
  • Function contents are consistently indented, including full-file closure wrappers.
  • Some whitespace rules differ to align with PHP WordPress standards, like the use of tabs or indenting.
  • jQuery’s 100-character hard-line limit, while encouraged, isn’t strictly enforced.

WordPress JavaScript coding standards cover the following areas:

  • Code refactoring.
  • Code spacing, including object declarations, arrays, and function calls:
// Object declarations
// DO
var obj = {
    name: 'John',
    age: 27,
    height: 179
}

// DON'T
var obj = {
    name: 'John',  age: 27,
    height: 179
}

// Arrays and function calls
// Include extra spaces around elements and arguments.
array = [ 1, 2 ];
foo( arg1, arg2 );
  • Semicolon use:
// Always use semicolons
array = [ 1, 2 ];
  • Indentation and line breaks, including blocks and curly braces, multi-line statements, and chained method calls:
// Use tabs for indentation
( function ( $ ) {
    // Expressions indented
    function doSomething() {
        // Expressions indented
    }
} )( jQuery );

// if, else, for, while, and try blocks should span multiple lines
if ( condition ) {
    // Expressions
} else if ( ( condition && condition ) || condition ) {
    // Expressions
} else {
    // Expressions
}

// Line breaks must occur after an operator if the statement
// is too long to fit on one line.
var html = '<p>The sum of ' + a + ' and ' + b + ' plus ' + c +
    ' is ' + ( a + b + c ) + '</p>';
/* If a chain of method calls is too long to fit on a single line, 
   use one call per line. The first call should be on a separate line from
   the object on which the methods are called. */
elements
    .addClass( 'foo' )
    .children()
        .html( 'hello' )
    .end()
    .appendTo( 'body' );
  • Assignments and globals, including declaring variables with const and let, declaring variables with var, globals, and common libraries.
  • Naming conventions like abbreviations and acronyms, class definitions, and constants:
// Abbreviations must be written in camelCase.
// All letters of acronyms should be capitalized.
const userId = 1;
const currentDOMDocument = window.document;

// Class definition must use UpperCamelCaseConvention.
class Human {
    ...
}

// Constants should use SCREAMING_SNAKE_CASE convention.
const SESSION_DURATION = 60
  • Equality:
// Use strict equality/inequality checks (=== and !==)
// instead of abstract checks (== and !=).
if ( name === "John" ) {
    ...
}
if ( result !== false ) {
    ...
}

// Also, with negation:
if !( result === false ) {
    ...
}
  • Strings:
// Use single-quotes for string literals.
    var myString = 'Hello world!'
  • Switch statements:
// Use a break for each case other than default.
// Indent case statements one tab within the switch.
switch ( event.keyCode ) {
    // ENTER and SPACE both trigger x()
    case $.ui.keyCode.ENTER:
    case $.ui.keyCode.SPACE:
        x();
        break;
    case $.ui.keyCode.ESCAPE:
        y();
        break;
    default:
        z();
}

Additionally, WordPress coding standards outline several best practices for writing JavaScript code.

As with PHP, WordPress provides inline documentation standards for JavaScript code. These inline standards, which are either formatted blocks of documentation or inline comments, follow the JSDoc 3 standard for inline JavaScript documentation. Inline standards cover functions, class methods, objects, closures, object properties, events, and file headers.

How to ensure accessibility in WordPress development

Accessibility standards are crucial for ensuring that digital content, including websites built on platforms like WordPress, is usable by people of all abilities. Adopting W3C’s accessibility standards ensures that websites created with WordPress are inclusive and accessible to individuals with disabilities.

The W3C accessibility guidelines, specifically the Web Content Accessibility Guidelines (WCAG), provide a comprehensive framework for making web content more accessible. Recognizing the importance of inclusivity, WordPress has incorporated these guidelines into its core functionalities.

For example, the WCAG measures compliance under the European Accessibility Act, which will apply to many organizations in the EU beginning June 2025.

Catering to diverse needs involves implementing features and design principles like screen reader compatibility, keyboard navigation, and text alternatives for non-text content.

Ensuring accessibility in WordPress isn’t just a matter of compliance. It’s a commitment to providing everyone with equal access to information and services. By adhering to W3C guidelines, WordPress websites become more accessible and user-friendly, fostering a more inclusive online environment.

Some practical examples of implementing accessibility features in your themes and plugins include the following:

  • Use semantic HTML — Ensure proper use of semantic HTML tags. For instance, use <nav> for navigation menus, <header> for site headers, and <main> for main content. These tags help screen readers and other assistive technologies understand the page’s structure.
  • Add text alternatives for images, video, and audio content — Provide descriptive alt text for images to convey their meaning to users who cannot see them. In WordPress, add descriptive alt attributes to the media library when adding images. Include captions and transcripts for videos and provide text alternatives for audio content to ensure users who are deaf or hard of hearing can access the information.
  • Build with responsive design in mind — Ensure your theme or plugin is responsive and adapts well to different screen sizes. This approach benefits users with various devices and ensures a consistent experience across platforms.
  • Design accessible forms — Provide clear labels and instructions for form fields. Use the appropriate input types, like email or phone, to trigger the correct keyboard on mobile devices and assistive technologies.
  • Use keyboard navigation — Ensure that all interactive elements are navigable using a keyboard. Users should be able to tab through links, buttons, and form fields. Test and enhance keyboard accessibility by avoiding reliance on mouse-only interactions.

Tools for adhering to WordPress coding standards

There are many code-sniffing tools available that can help you adhere to the platform’s coding standards outlined above. Let’s review just a handful of the validation tools you can use to check for WordPress coding standards.

PHP_CodeSniffer

The PHP_CodeSniffer scans your PHP codebase to identify deviations from the established norms. It facilitates cleaner, more efficient code by pinpointing coding infractions and style discrepancies. This leads to enhanced performance of WordPress websites and ensures seamless compatibility with future updates and plugins.

W3 Org’s CSS Validation Service

W3 Org’s CSS Validation Service scans CSS style sheets, identifying and rectifying potential errors that could impede optimal site performance. It plays a crucial role in maintaining consistency and adherence to W3C standards, guaranteeing a smooth user experience across various devices. As a result, websites see improved loading times and meet the stringent CSS coding standards set by WordPress.

JSHint

JSHint analyzes JavaScript code, identifying potential errors, stylistic inconsistencies, and adherence to best practices. It helps you to write cleaner, more efficient code, ultimately optimizing the website’s performance. Its keen focus on WordPress coding standards ensures JavaScript code seamlessly integrates with the overall architecture of WordPress, helping you maintain a cohesive and standardized coding environment.

WebAIM Contrast Checker

WebAIM’s Contrast Checker helps you assess and improve the accessibility of your WordPress websites. This tool simplifies the often complex process of achieving optimal color contrast to promote accessibility. Using the contrast checker’s real-time feedback, you can identify areas to improve text legibility and readability for all visitors.

Summary

Coding standards are the backbone of efficient and collaborative software development. They ensure consistency and readability in code, streamline the coding process, enhance maintainability, and facilitate teamwork. For WordPress developers, adhering to coding standards is crucial for creating robust and scalable websites.

Kinsta can help in your efforts to meet standards like these by supporting development environments that allow you to focus on your work. Our own Docker-based DevKinsta suite allows you to design and develop WordPress sites on your local machine and then deploy seamlessly to your production environments. Combine DevKinsta with our Managed WordPress Hosting, and you’ll be able to spend more time with your code and less time configuring web servers.

Steve Bonisteel Kinsta

Steve Bonisteel is a Technical Editor at Kinsta who began his writing career as a print journalist, chasing ambulances and fire trucks. He has been covering Internet-related technology since the late 1990s.