An Overview of WordPress Coding Standards

An Overview of WordPress Coding Standards provides a comprehensive introduction to the important guidelines and conventions that developers must follow when writing code for WordPress development. These coding standards play a crucial role in promoting collaboration, streamlining maintenance, and ensuring the reliability of the codebase. By adhering to these standards, developers can improve code quality, enhance communication among team members, and maintain consistency across projects. The article explores the coding standards for PHP, HTML, CSS, JavaScript, and Accessibility in detail, providing valuable insights and recommendations for building compliant websites and contributing to the WordPress development community. Additionally, it discusses the inline documentation standards for PHP code and emphasizes the significance of adhering to HTML and CSS coding standards in WordPress themes and plugins.

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. 

An Overview of WordPress Coding Standards

DO

function foo() { ?>

?php>
>

DON'T

if ( $x === $y ) { ?>

ode>
// Avoid shorthand PHP tags 

An Overview of WordPress Coding Standards

## DO ## DON'T ... ?> esc_html( $x ); ?> ?>?>?php>?php>
// 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' => 'john@example.com', '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.
 

Descriptive text

Click here

  • Quotes – All attributes must have a value and must use single or double quotes. Failing to quote the values can lead to security vulnerabilities.
   

  • 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.
  

Not Found

No results were found.

?php>

Not Found

No results were found.

?php>
?php>?php>?php>?php>

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....