Quick contact info

Introducing a truly professional WordPress theme built to last! We developed Wilmër for all construction & architecture sites.

In-Depth Guide On WordPress Coding Standards For PHP, HTML, JS & CSS

By Piyali Sarkar WordPress 67 Views

This quote is good enough to understand the importance of standards as far as the coding is concerned. Every programming language has its own rules and regulations for the 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; they are more of coding conventions that if supported by the programmer can help them to enhance their coding style.

The same applies to the case of WordPress where it has its coding standards which 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

Here’s how we will progress right through the WordPress Coding Standards series :

Part 1: In-Depth Guide On WordPress Coding Standards For PHP & HTML
Part 2: In-Depth Guide On WordPress Coding Standards For CSS & JS

In this blog, we will focus on part 1 – WordPress Coding Standards For PHP & HTML and in the next blog, we will focus on part 2 – WordPress Coding Standards For CSS & JS.

Before going into the details of WordPress Coding Standards, you need to know the purpose of the coding standards & why you need to have coding standards.

What Is The Purpose Of WordPress Coding Standards?

Wordpress Coding

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.

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

WordPress Coding Standards For PHP

1. Using Single & Double Quotes

If you’re someone who is working as a WordPress Developer, then you must be knowing that 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.

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

3. 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 } ?>
4. Use elseif, Not else if

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

5. Multi-line Function Calls

As a WordPress developer, when you split the function call over the 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: Top 11 RSS Feed Plugins For WordPress In The Year 2019

6. Regular Expressions

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.

To know more about regular expression, you can Hire WordPress Developer from any reputed organization. He/She should be able to guide regarding this subject with utmost ease.

7. 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 ; ?>" />
8. No Shorthand PHP Tags

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

Example: (Incorrect)

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

Example: (Correct)

<?php ... ?>
<?php echo $var; ?>
9. 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.

10. 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;
}
11. 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.

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

13. 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 which is unambiguous & self-documenting.

Example:

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

For class name, you should use capitalize words which are separated by underscores.

Example:

class Walk_Categorization extends Walk { [...] }

All the constants should be in 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.

14. 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’ );
15. 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 );
16. Ternary Operator

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

Example :

$musictype = ( 'jazz' == $music ) ? 'cool' : 'blah';
17. 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.

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

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

2. 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
3. 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
4. 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.

5. Indentation

Any Custom WordPress Development 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; ?>

Conclusion

Every programming language has its coding standards which need to be followed by the programmer to enhance the readability of the code. The same is the case with WordPress, where there are coding standards for PHP, HTML, CSS & JS.

Here, we have tried to provide you with an in-depth guide on WordPress Coding Standards For PHP & HTML which will help you in future when you’re developing something in WordPress.

If you’ve any question or suggestion regarding this subject, then do mention them in our comment section. Thank You!

Disclaimer: We at eSparkBiz Technologies have created this blog with all the consideration and utmost care. We always strive for excellence in each of our blog posts and for that purpose, we ensure that all the information written in the blog is complete, correct, comprehensible, accurate and up-to-date. However, we can’t always guarantee that the information written in the blog correct, accurate or up-to-date. Therefore, we always advise our valuable readers not to take any kind of decisions based on the information as well as the views shared by our authors. The readers should always conduct an in-depth research before making the final decision. In addition to these, all the logos, 3rd part trademarks and screenshots of websites & mobile apps are the property of the individual owners. We’re not associated with any of them.

Piyali Sarkar

Piyali Sarkar

Piyali, an M.Tech in CSE, has experience ranging from an assistant professor to creative writing in the local newspapers, she has stepped fully into the domain of mobile application development. Her writing can be said to be a combo of crazy thought process, efficacious vocab & sublime modus operandi. She pens down her thought for eSparkBiz @Mobile App Development Company where you can Hire Mobile App Developer. In an app-centric world, having a hot app-o-lava in her mind, she loves sharing her diegesis.

Search

Follow us

Subscribe Newsletter

Call us Today

Got any Questions?
call us Today!

+1 408 850 1488 [email protected]

Related Post

Top 8 Cryptocurrency & Bitcoin Plugins For WordPress

Top 8 Cryptocurrency & Bitcoin Plugins For WordPress

“BITCOIN is a remarkable cryptographic achievement and the ability to create something that is not duplicable in the digital world has enormous value.” - Eric…

How To Make Millions By Starting A Travel Blog In WordPress – 2019?

How To Make Millions By Starting A Travel Blog In WordPress – 2019?

It clearly shows that you should also opt for WordPress for starting your travel blog. Taking this into consideration, today we’re going to provide you…

11 Simple Strategies To Make Your WordPress Website Accessible

11 Simple Strategies To Make Your WordPress Website Accessible

Web Accessibility Guidelines Web Accessibility means everyone who visits your website should be able to access everything. Even if the person has a condition that…