An Introduction to the WordPress PHP Coding Standards

An Introduction to the WordPress PHP Coding Standards • WPShout

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

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.

Keep reading the article at WPShout. The article was originally written by Lea Cohen on 2020-12-08 10:55:01.

The article was hand-picked and curated for you by the Editorial Team of WP Archives.

Disclosure: Some of the links in this post are "affiliate links." This means if you click on the link and purchase the product, We may receive an affiliate commission.

Leave a Comment

Your email address will not be published. Required fields are marked *

Show Your ❤️ Love! Like Us
Scroll to Top