Skip to content

An Introduction to the WordPress PHP Coding Standards

Coding makes you follow rules – every language has its own syntax to which you have to adhere if you want your code to compile or run. But there is another set of rules, that while isn’t essential for the actual running the code, helps in peripheral parts of coding. These rules are called Coding Standards.

Coding standards are recommended conventions for writing code. Every language has its own, and WordPress, as a system, has its own version for each of the languages used to build it. WordPress has coding standards for PHP, Accessibility, CSS, HTML, and JavaScript.

This article will focus on the PHP coding standards. Before we dive into the coding standards, you might want to brush up on the PHP language through the PHP for Beginners tutorial, The Essential WordPress Tutorial for PHP Developers, or specifically Understanding PHP’s echo.

Why Follow the WordPress Coding Standards

You might be asking yourself: why would I want to commit to a whole set of new rules that aren’t absolutely needed for writing working code on WordPress. Well, that’s a great question, and one that The WordPress Coding Standards documentation has answered in its introduction:

Coding standards help avoid common coding errors, improve the readability of code, and simplify modification. They ensure that files within the project appear as if they were created by a single person. Following the standards means anyone will be able to understand a section of code and modify it, if needed, without regard to when it was written or by whom. If you are planning to contribute to WordPress core, you need to familiarize yourself with these standards, as any code you submit will need to comply with them.

The WordPress Coding Standards documentation

The Logic Behind the Rules

In this article, we’ll look at some of the coding standards, and try to understand what problem they’re trying to solve, i.e., what the motivation is behind those rules. The categories of motivations that appear in this article are:

Error Prevention

When writing code, we want our habits to keep us away from errors as much as possible. The following rules help in that.

  • Brace Style – The most important convention regarding Braces is that they should always be used, even when they are not required. This is in order that if in the future code is added to the statement that is executed in the case of the condition, you won’t have to remember to add braces around the whole statement – the braces will already be there, and all you have to do is add your code inside them.
  • Remove Trailing Spaces – As per the PHP docs, “If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.” While WordPress doesn’t forbid using the closing tag, it does require removing trailing spaces after it.
  • Formatting SQL statements – When inserting data into the database, the most important security measure is to sanitize the data, that is, make sure that no malicious code is inserted. The way to do that is to escape the data, and WordPress has a few functions that do that. According to the WordPress Coding Standards, escaping should be done as close to the time of the query as possible, preferably by using $wpdb->prepare(). The Coding Standards documentation sends the developer to read more about escaping in the Data Validation part in the Codex.
  • Yoda Conditions – When coding a condition (if ($x==3)) that compares a variable with a value, we use a double equals sign. But we could easily accidentally omit an equals sign, which would result in the value being assigned to the variable, which is most likely an unwanted consequence. The PHP parser wouldn’t warn us about that since it’s perfectly legal, even if not desirable, to do so. A good way to prevent such an error is to always put the variable on the right side and put constants, literals, or function calls on the left side. This way, accidentally omit an equals sign you’ll get a parse error, because you can’t assign to a constant This type of condition is called Yoda conditions, and the WordPress Coding Standards requires you to write your conditions this way.

Readability

Easier readability means that when you read code that you haven’t written, you can scan it easily and focus on what it does, rather than try to decipher where is starts and ends, have to overcome alignment issues, and get over other visually distracting matters.

  • Defining arrays – An array can be created using the array() language construct. But there exists a short array syntax that replaces array() with []. The WordPress Coding Standards recommend using the long array syntax since it is generally more readable than short array syntax, particularly for those with vision difficulties. Additionally, it’s much more descriptive for beginners.
  • The Opening and Closing PHP Tags rule is there to enhance readability. The rules require that when embedding multi-line PHP snippets within an HTML block, the PHP open and close tags must be on a line by themselves. Applying this rule helps follow the interleaving of PHP in HTML, and quickly notice if any PHP tag is missing.
  • Use elseif, not else if – PHP allows 2 kinds of syntax for control structures (if, while, for, foreach, and switch). The first kind is the usual one, using opening and closing braces. The second one is called alternative syntax for control structures which means that the basic form of this syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively. Since the WordPress Coding Standards allow using the alternative syntax, and that syntax isn’t compatible with else if, the WordPress Coding Standards dictate using elseif, not else if in order to always be compatible with both types of control structures syntax.
  • Naming Conventions: The main goal of naming conventions is to reduce the effort needed to read and understand source code (you can find other goals here). Therefore, the specific rules don’t matter – what matters is that everyone follows them,
    • lowercase letters in variable, action/filter, and function names and separate words via underscores.
    • Class names should use capitalized words separated by underscores.
    • Constants should be in all upper-case with underscores separating words.
    • File name conventions too.
  • The Self-Explanatory Flag Values for Function Arguments – PHP doesn’t support named arguments (function calls that clearly state the name of each parameter within the function call), and therefore when we see a function call, we don’t know what the values in it mean unless we search for the function definition. The code can be made more readable by using descriptive string values, instead of booleans. For example, defining a function’s arguments this way: function eat( $what, $speed = ‘slowly’ ) results in clear functions call: eat( ‘mushrooms’, ‘slowly’ ); . This is clearer than this function definition: function eat( $what, $slowly = true ) because its function call uses a boolean value: eat( ‘mushrooms’, true ); which is unclear if you don’t remember the function’s definition.
  • The Coding Standards allow using the ternary operators, but they restrict their usage to having them test if the statement is true, not false. Otherwise, it just gets confusing. (An exception would be using !empty(), as testing for false here is generally more intuitive.)
  • No use of Clever Code – This rule covers a lot of ground, having many examples of code all of whose common denominator is that it’s succinct but confusing. The WordPress Coding Standards will always prefer readability over cleverness or brevity. Clever code includes things such as
    • using the || operator in chacking a variable’s existence,
    • loose comparisons ( a double equals sign (==) instead of a triple equals sign (===)),
    • placing assignments in conditionals,
    • goto statements,
    • the eval() construct,
    • the create_function() function One “clever” code that is allowed, albeit having to explicitly comment it, is in a switch statement, it’s okay to have multiple empty cases fall through to a common block. If a case contains a block, then falls through to the next block.
  • Formatting SQL statements – another rule regarding SQL statements is that when formatting SQL statements you may break it into several lines and indent if it is sufficiently complex to warrant it. Most statements work well as one line though. Always capitalize the SQL parts of the statement like UPDATE or WHERE.

Easier Maintenance

  • Anonymous Functions are allowed, just must not be passed as filter or action callbacks, as they cannot be removed by remove_action() / remove_filter().
  • Older versions of PHP don’t support Shorthand PHP Tags and therefore no such tags are allowed.
  • Interpolation for Naming Dynamic Hooks – Dynamic hooks are hooks that include dynamic values in their tag name, e.g. {$new_status}_{$post->post_type} (publish_post). These hooks should be constructed by inserting the variables between the constants, and not by concatenating them as strings. The WordPress Coding Standards explain exactly how to construct them technically, but also adds a content-wise rule – that where possible, dynamic values in tag names should be as succinct and to the point as possible. $user_id is much more self-documenting than, say, $this->id.
  • Error Control Operator @

As noted in the PHP docs:

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

While this operator does exist in Core, it is often used lazily instead of doing proper error checking. Its use is highly discouraged, as even the PHP docs also state:

  • Don’t extract() – extract is a function that imports variables into the current symbol table from an array. That means that after its use, new variables are suddenly introduced, without it being obvious from the code how they came to be. It makes code harder to debug and harder to understand, as is elaborated by Joseph Scott.

Some rules are there to make the code look consistent across all developers and developing platforms. These are rules which on the one hand we can live perfectly well without and nothing would happen to the code, but had they not existed, every developer could make their own decisions regarding the code format, but then the code would look different between developers. While such differences aren’t ground breaking, they still might cause discomfort, for example when comparing 2 versions of the same file, etc. So in the name of Code Consistency, the WordPress Coding Standards saves you having to make those decisions – you just apply the rules and don’t give it another thought.

Formatting Consistency, or Eliminating Decisions

  • In the matter using single or double-quotes, the WordPress Coding Standards say that if you’re not evaluating anything in the string, use single quotes. It also advises that you should almost never have to escape quotes in a string, because you can just alternate your quoting style, like so:
    echo '<a href="/static/link" title="Yeah yeah!">Link name</a>' echo "<a href='$link' title='$linktitle'>$linkname</a>";
  • In the famous tabs-vs-spaces war, which really has almost no consequence (even though the Silicon Valley protagonist split up with a girl over it), the WordPress Coding Standards rule of thumb is that tabs should be used at the beginning of the line for indentation, while spaces can be used mid-line for alignment. Braces position should be on the same line with the command that triggers them.
  • In the matter of Multiline Function Calls, there really isn’t any impact on the running of the code, but still, a decision was made that should eliminate the need for developer local decisions: When splitting a function call over multiple lines, each parameter must be on a separate line. Single line inline comments can take up their own line.
  • The coding standards makes you remove trailing whitespace at the end of each line of code.
  • The placing of spaces doesn’t have any impact other than neatness, but there are many rules regarding that spaces be used after commas, on both sides of operators, on both sides of the opening and closing parentheses, and many more cases that are detailed here.
  • Formatting SQL statements – Always capitalize the SQL parts of the statement like UPDATE or WHERE.
  • Regular Expressions – There are 2 standardized syntaxes for regular expressions: the POSIX one (POSIX standing for Portable Operating System Interface, meaning that it’s aimed at maintaining compatibility between operating systems) and the PCRE one (PCRE standing for Perl Compatible Regular Expressions). The WordPress Coding Standards state that the preferred method is the PCRE one. In addition, it says that you should never use the /e switch, use preg_replace_callback instead; it also goes on to explain why you should use single-quoted strings for regular expressions.

How to Integrate the WordPress Coding Standards in Your Coding Routine

Of course, no one expects that you remember all these rules when you’re writing code. The best way to integrate them is through your IDE, and if that isn’t possible, then through an external tool

PHP_CodeSniffer

PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files to detect and fix violations of a defined set of coding standards. Here are WordPress Coding Standards for PHP_CodeSniffer

Integrate the Coding Standards in PHPStorm

Here are resources guiding you how to integrate the WordPress Coding Standards in PHPStorm:

VS Code

VS Code also has a way of Setting up WordPress Coding Standards for your Site, Theme, or Plugin using VS Code.

Summary

In this article we reviewed some of the WordPress Coding Standards regarding PHP, to better understand where they come from, what their goals are, and why we should follow them

This article is by no means an exhaustive account of the WordPress Coding Standards. I wholeheartedly recommend you hop over to the WordPress PHP Coding Standards documentation and divulge all its secrets.

Yay! 🎉 You made it to the end of the article!
Lea Cohen
Share:

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Pexle Chris
December 13, 2020 2:50 am

Great article. Thank you. I haven’t known some of these best practises!!

JB van der Westhuizen
December 10, 2020 2:05 am

I am new to messing with the WordPress code but I decided that I should learn some PHP. I came across your website and I am starting the “PHP for Beginners: Starting on Back-end WordPress Development” course today.

But I could already see some of the standards just with my limited experience messing with theme’s PHP code.

I’ll keep this in mind while learning.

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!

4
0
Would love your thoughts, please comment.x