Every programming language has its own rules and regulations for coding, which is also known as the coding standards.

Each programmer should follow these coding standards to inherit the best practices in his/her professional career. Coding standards are not the syntax that you need to follow strictly; therefore expert WordPress developers highly prefer following the coding conventions as it helps them to be accurate and enhance their coding styles, you can easily hire WordPress developers who are proficient in working with the coding standards.

The same applies to the case of WordPress where it has its coding standards that every developer should know. Taking this into consideration, we have developed a two-part series on WordPress Coding Standards which will help you to see the coding standards for PHP, HTML, CSS, & JS.

“Any Fool Can Write a Code That Computer Can Understand. Good Programmers Write Code That Human Can Understand.”

– John Johnson

What Is The Purpose Of WordPress Coding Standards?

The sole purpose of the WordPress Coding Standards is to create a base for collaboration and review within the various aspects of the WordPress open-source project & community right from the core part to the themes and plugins.

Why You Need Coding Standards?

Coding standards help you to avoid common errors, simplify the modification process & most importantly assists you in improving the readability of your code.

In addition to all these, the coding standards ensure that all files within one project appear as if a single person creates them.

Another significant advantage you get by following the coding standards is that anyone will be able to understand your code and also modify it, without contacting you.

So, if you’re planning to develop a website in WordPress, you should know the coding standards. Now, let’s dive deep into the core part & understand the various coding standards.

In-Depth Guide On WordPress Coding Standards For PHP & HTML:-

WordPress Coding Standards For PHP
 Using Single & Double Quotes

If you’re someone who is working as a WordPress Developer, then you must be knowing that the appropriate use of single and double quotes is necessary.

As per the standard convention, if you’re not evaluating anything in the string, then you should use the single quotes. Otherwise, you should always prefer using the double quotes for the string value while writing PHP code for the WordPress platform.

Example:

echo 'Contact Us';
echo "$cta_label";

Here, we have used double quotes for displaying the “Contact” as it is a value for the title attribute, while we have used a single citation for ‘$cta_title’ as we’re not evaluating its value.

Indentation

Another significant thing that you need to remember while writing the code in PHP is the proper use of indentation. The reason behind that is, it always reflects the logical structure of your code. Still use tabs for indentation instead of space, as it improves readability.

However, there is one exception: If you’ve got a block of code that looks more readable if one can write the code in an aligned manner, then you can use space for that purpose.

Example:

[tab]'demo' => 'demovalue';
[tab]'demo1' => 'demovalue1’;
[tab]'demo2' => 'demovalue2';
[tab]'demo3' => 'demovalue3';

For associative arrays, each item should start on a new line when the array contains more than one element:

Example:

$key_value_array = array(
[tab]'demo' => 'demovalue',
[tab]'demo1' => 'demovalue1',
[tab]'demo2' => 'demovalue2',
[tab]'demo3' => 'demovalue3',
);

Here, you may have noted a comma after the last thing. WordPress recommends it as it makes it easier for you to change the order of an array.

Example:

[tab]'demo3' => 'demovalue3',
[tab]'demo1' => 'demovalue1',
[tab]'demo' => 'demovalue',
[tab]'demo2' => 'demovalue2',
);

For the switch structures, the case should be indented one tab from the switch statement and break should be one tab from the case statement.

Example:

switch ( $condition ) {
[tab]case 'value':
[tab][tab]demo_function();
[tab][tab]break;
[tab]case 'value2':
[tab][tab]demo_function1();
[tab][tab]break;
}

As a thumb rule, you should use tabs at the beginning of the line for indentation and Space should be used for the mid-line alignment.

Brace Style

Braces should be used for all the blocks as shown in the snippet below:

Example:

if ( condition ) {
function();
function2();
} elseif ( condition2 && condition3 ) {
function3();
function4();
} else {
defaul_function();
}

In case, you have a long block; it can be broken into 2 or more shorter chunks to reduce complexity and improve readability.

Example:

if ( condition ) {
function();
function2();
} elseif ( condition2 && condition3 ) {
function3();
function4();
} else {
defaul_function();
}
foreach ( $data as $data_key => $data_value ) {
echo $data_value;
}

One thing that should be noted here is that the use of braces is to avoid single-statement inline control structures. You’re free to use the alternative syntax for control structure, especially when you embed the PHP code into the HTML.

Example:

<?php if ( !empty( $data ) ) { ?>
    <div class="test">
        <?php foreach ( $data as $data_key => $data_value ) { ?>
            <div id="data-<?php echo $data_key; ?>">
                <!-- Other Content -->
            </div>
        <?php } ?>
    </div>
<?php } ?>
Use elseif, Not else if

else if is not compatible with the colon-based syntax for if|elseif blocks. Therefore, you should always use else if instead of using else if.

Multi-line Function Calls

As a WordPress developer, when you split the function call over multiple lines, always remember to keep each parameter on a separate line.

Each parameter should not consume more than one line, and you should assign a value to multiline parameter, so you need to pass that variable to the function call.

Example:

$bar = array(
'use_this' => true,
'meta_key' => 'field_name',
);
$baz = sprintf(
/* translators: %s: Friend's name */
esc_html__( 'Hello, %s!', 'yourtextdomain' ),
$friend_name
);

$a = foo(
$bar,
$baz,
/* translators: %s: cat */
sprintf( __( 'The best pet is a %s.' ), 'cat' )
);

Read also: How To Bulk Upload Files To WordPress Website

 Regular Expressions

regular-expression

Always use Perl compatible regular expressions (PCRE) with reference to their POSIX counterparts. Never use the /e switch, use preg_replace_callback instead. In addition to all these, you should always use single-quoted strings for regular expressions.

Opening & Closing PHP Tags

When you’re embedding multiline PHP snippets within an HTML block, the PHP open and close tags must be on a line by themselves.

Example: (multiline)

function test_function() {
    ?>
        <div>
        <?php
            echo '<a href="www.url.com" title="Contact">Contact Us</a>';
        ?>
        </div>
    <?php
}

Example: (single line)

<input type="text" name="<?php echo  $name ; ?>" />
No Shorthand PHP Tags

Never use shorthand PHP tags, always use full PHP tags.

Example: (Incorrect)

<? ... ?>
<?= $var ?>

Example: (Correct)

<?php ... ?>
<?php echo $var; ?>
Remove Trailing Spaces

Always remember to remove the trailing whitespaces at the end of your each coding line. You should omit the PHP tag at the end of the file. However, if you’re using the tag, then don’t forget to remove the trailing whitespace.

Proper Usage Of Space

Always put space after every comma and also on both sides of logical, comparison, string and assignment operators.

Example:

y == 2
foo && bar
! foo
array( 1, 2, 3 )
$baz . '-4'
$term .= 'Z'

Remember to put spaces on both sides opening and closing parentheses of if, elseif, foreach, for, and switch blocks.

Example:

foreach ( $foo as $bar ) { …

Also, follow this rule while defining a function.

Example:

function dummy( $param1 = 'foo', $param2 = 'bar' ) { ...
 
function my_dummy_function1() { ...

When you’re calling any function, you need to follow the rule mentioned above.

Example:

first_function1( $param1, func_param( $param2 ) );
my_dummy_function();

For logical comparisons, the same rule applies.

Example:

if ( ! $foo ) { ...

When you’re performing typecasting, the above rule is also valid.

Example:

foreach ( (array) $foo as $bar ) { ...
 
$foo = (boolean) $bar;

When referring to array items, include space around the index only if it’s variable.

Example:

$x = $foo['bar']; // correct
$x = $foo[ 'bar' ]; // incorrect
 
$x = $foo[0]; // correct
$x = $foo[ 0 ]; // incorrect
 
$x = $foo[ $bar ]; // correct
$x = $foo[$bar]; // incorrect

For a switch block, there should be any space before the colon for a case statement.

Example:

switch ( $foo ) {
    case 'bar': // correct
    case 'ba' : // incorrect
}

Similarly, there should be no space before the colon on the return type declaration.

Example:

function sum( $a, $b ): float {
    return $a + $b;
}
Formatting SQL Statements

When you’re formatting any SQL statement, you should break it into several lines and indent if it’s sufficiently complex. Always capitalize on the SQL parts of the statements such as WHERE or UPDATE.

Functions that update the database should expect their parameters to lack SQL slash escaping when passed. For that purpose, escaping should be done by using $wpdb->prepare().

$wpdb->prepare() is a method that handles escaping, quoting and int-casting for SQL queries.

Example:

<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'miles';
$allmiles = $wpdb->get_var( $wpdb->prepare( 
  "
    SELECT sum(meta_value) 
    FROM $wpdb->postmeta 
    WHERE meta_key = %s
  ", 
  $meta_key
) );
echo "<p>Total miles is {$allmiles}</p>";
?>

Here, %s is for string placeholders, and %d is used for integer placeholders. Note that they are not ‘quoted’! $wpdb->prepare() will take care of escaping and quoting for us. It is the benefit you get if you utilize this function.

Database Queries

Always avoid directly touching the database. Utilize the functions for extracting the data whenever possible. The reason behind that is, Database Abstraction (using functions in place of queries) helps you to keep your code forward-compatible.

Naming Conventions

Always use lowercase for a variable, action/filter, and function names. Separate the words by using underscore. In addition to that, choose a name that is unambiguous & self-documenting.

Example:

function some_name( $some_variable ) { [...] }

For class names, you should use capitalize words that are separated by underscores.

Example:

class Walk_Categorization extends Walk { [...] }

All the constants should be in the upper-case with two words separated by underscores.

Example:

define( 'PI', true );

The file should be named descriptively by using the lowercase, and for separating the words, you should utilize hyphen.

My-new-theme.php

For class file name should be based on the class name, i.e., class- followed by a hyphen.

Example:

If the class name is class Walk_Categorization, then the class file name should be class-walk-categroization.php

There is one exception in the class file name for three files: class.wp-dependencies.php, class.wp-scripts.php, class.wp-styles.php. These files ported into Backpress and therefore, prepended with class, instead of a hyphen.

Self-Explanatory Flag Values for Function Arguments

Always prefer using true & false for the string values when you’re calling a function.

Example :

// Incorrect
function eat( $what, $slowly = true ) {
...
}
eat( 'wheat', true );
eat( 'rice', false );

Now, PHP doesn’t support flag arguments, and therefore, sometimes the values of flags are meaningless as it is in our example shown above. So, for that type of scenario, you should make your code readable by utilizing descriptive string values instead of booleans.

Example:

// Correct
function eat( $what, $slowly = ‘slowly’) {
...
}
eat( 'wheat', ‘slowly’ );
eat( 'rice', ‘quickly’ );
Interpolation for Naming Dynamic Hooks

For naming the dynamic hooks, you should utilize the interpolation methodology rather than using the concatenation for readability purpose. Dynamic hooks are the one which includes dynamic values in their tag name – {$new_status}_{$post->post_type} (publish_post).

Always include the variables of your hook tags inside the curly braces {} and the outer tag name should be wrapped in double quotes. The reason behind following this methodology is to ensure that PHP can correctly parse the variable types with interpolated string:

Example:

do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
Ternary Operator

For using the ternary operator, always have them tested if the statement is true, not false. Otherwise, it can create massive confusion in the future.

Example :

$musictype = ( 'jazz' == $music ) ? 'cool' : 'blah';
Yoda Conditions

When you’re making the logical comparisons which include variables, always put the variable on the right-hand side & constants, literals, or function calls on the left-hand side. If neither side has a variable, then the order is not that important.

Example:

if ( true == $the_force ) {
    $victorious = you_will( $be );
}

Here, if you omit an equals sign (=), then you will get a parse error, as you can’t assign a value to constant like true. Instead of that, if you’ve written ( $the_force = true ), the assignment would be perfect, and you won’t get an error. This is known as the Yoda Condition and it applies to ==, !=, ===, !==, <, >, <= or >= operators.

Clever Coding

For coding, readability is more important than cleverness.

Example :

isset( $var ) || $var = some_function();

It might look clever, but it has low readability. Instead of that, if you write:

if ( ! isset( $var ) ) {
    $var = some_function();
}

Then, readability improves drastically.

In the case of a switch statement, it’s ok to have multiple instances in a standard block. However, if an argument contains a block, the falls through to the next block, then this should be explicitly commented as shown in the snippet below:

switch ( $foo ) {
    case 'bar':     // Correct, an empty case can fall through without comment.
    case 'baz':
        echo $foo;  // Incorrect, a case with a block must break, return, or have a comment.
    case 'cat':
        echo 'mouse';
        break;      // Correct, a case with a break does not require a comment.
    case 'dog':
        echo 'horse';
        // no break   // Correct, a case can have a comment to explicitly mention the fall-through.
    case 'fish':
        echo 'bird';
        break;
}

WordPress Coding Standards For HTML

Validation

All the HTML pages should be verified with the help of the W3C Validator to ensure that markup is well-formed. Although this is not the only indicator of proper coding, it helps to solve the problems tested via the automation process. The manual code review cannot be as useful as this one and that’s why it is recommended that you should validate your code.

Self-Enclosing Elements

You need to close all the tags. However, for the tags that are self-enclosing, the forward slash should have once space preceding it.

Example:

<br /> //Correct
<br/> //Incorrect

Attributes & Tags

All the tags, as well as their attributes, must be written in lowercase. In addition to that, attribute values should be in lowercase when the purpose of the text is just to be interpreted by a machine.

However, when an attribute value is read by a human, proper capitalization should follow:

Example:

<meta http-equiv="content-type" content="text/html; charset=utf-8" /> // For Machine
<a href="http://abc.com/" title="Content Writer">ABC.com</a> // For Human

Quotes

As per the W3C specification for XHTML, all the attributes must have value & must be wrapped inside single or double quotes.

Example:

<input type="text" name="ABC" disabled="disabled" /> //Correct
<input type='text' name=’ABC’ disabled='disabled' /> //Correct

<input type=text name=email disabled>//Incorrect

However, in HTML, all attributes do not have to have values & therefore, no need to use quote for that. But you should follow these conventions to avoid any kind of security vulnerabilities.

Indentation

Any WordPress Company would tell you the importance of indentation in coding. Like PHP, HTML indentation should still reflect a logical structure. So always use tabs and not spaces. If you’re mixing PHP & HTML, then indent PHP blocks to match the HTML code.

Example:

?php if ( ! have_posts() ) : ?>
    <div id="post-1" class="post">
        <h1 class="entry-title">Not Found</h1>
        <div class="entry-content">
            <p>Apologies, but no results were found.</p>
            <?php get_search_form(); ?>
        </div>
    </div>
<?php endif; ?>