Thursday, November 21, 2024
HomeEveryday WordPressAn introduction to WordPress coding standards

An introduction to WordPress coding standards


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() {
  ?>
  
// Avoid shorthand PHP tags

## DO



## DON'T


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



Source link

RELATED ARTICLES
Continue to the category

LEAVE A REPLY

Please enter your comment!
Please enter your name here


Most Popular

Recent Comments