Advertisement
Cheat Sheets

The WordPress Coding Standards: Braces, Regular Expressions, and PHP Tags

by

In this series, we've been taking a deep dive into the WordPress Coding Standards in order to get the word out about them, understand them, and begin to practically apply them in our day-to-day work.

If you're just joining the series, so far we've covered the following topics:

  • Naming Conventions and Function Arguments
  • Single Quotes and Double Quotes
  • Indentation, Space Usage, and Trailing Spaces

In this article, we're going to continue building on top of the content in the previous article: Specifically, we're going to be taking a look at brace style, regular expressions, and nuances of working with PHP tags within the context of building WordPress themes, plugins, and applications.


Why Style Matters

Throughout this series, one of the issues that we've reiterated over and over is that coding standards help to make code more readable, maintainable, and that they should ultimately make it look like one developer has written the code.

But one of the things that we haven't actually talked much about is why style matters. First, though, this raises the question: what's the difference between style and coding conventions?

Honestly, I think that some would say that there is no difference - in fact, they'd say that they are synonymous. I don't necessarily agree. Personally, the way that I've always viewed it is that the coding standards define the style of the code that's being written. Coding standards are the conventions by which we style our code.


Brace Style

So with that said, let's resume our conversation on coding conventions by looking at how the WordPress Coding Standards define the usage of braces.

Generally speaking, the rules are simple:

  • Single line blocks can omit braces
  • Multiline blocks should always include braces
  • When you have excessive multiline conditionals, consider breaking up the conditionals into their own functions to minimize the block

These principles are often best demonstrated in code. The first two are simple:

// Single Line conditional examples
if ( condition1 )
	do_work();

if ( condition1 )
	do_work();
else
	dont_do_work();

// Multiline conditionals
if ( condition1 ) {

	do_work();
	do_more_work();

} else {

	dont_do_work();
	seriously_be_lazy();

}

// Single Line loops (true for do/while, while, for, and foreach)
while ( condition1 )
	dont_stop_believing();

// Single Line loops (true for do/while, while, for, and foreach)
while ( condition1 ) {

	dont_stop_believing();
	hold_on_to_that_feeling();

}

Nothing terribly complicated, right?

In fact, you can see that I used methods in the blocks above. Which is what leads us to our next principle: If you have an overly complicated body in your conditional, it will likely help to refactor the conditional for easier readability.

Let's take a look at an example.

Before

In this example, we're going to iterate through the meta data of the current user, and, if the current user's meta key has the substring of "destroy:" then we'll delete that user's meta key.

Notice in this example that all of this work is being done in a conditional, in a foreach loop, and then in another conditional.

// If condition1 is true...
if ( condition1 ) {

	// ...then get the user meta data for the current user
	foreach( get_user_meta( wp_get_current_user()->ID ) as $meta_key => $meta_value ) {

		// If user has a destroy value set, delete it. This means they opted not to delete a user.
		if( strstr( $meta_key, 'destroy:' ) ) {
			delete_user_meta( wp_get_current_user()->ID, $meta_key );
		}

	}

}

Lots of nested code, right?

After

There's a variety of ways that this can be refactored. In fact, some developers will go as far as taking each block and abstracting it into its own method - there's nothing wrong with that, either.

But in order to demonstrate this point, we're only going to provide one level of abstraction: We're going to take the loop and the inner conditional, move it to a function that accepts a user, and then perform the original action.

// If condition1 is true...
if ( condition1 ) {
	process_user( wp_get_current_user() );
}

function process_user( $user ) {

	// Get the user meteta data for the current user
	foreach ( get_user_meta( $user->ID ) as $meta_key => $meta_value ) {

		// If user has a destroy value set, delete it. This means they opted not to delete a user.
		if ( strstr( $meta_key, 'destroy:' ) ) {
			delete_user_meta( $user->ID, $meta_key );
		}

	}

}

Like I said, this is a relatively simple example, but the point remains: Moving a large block of a code into its own, specialized function can go a long way to refactor the conditional so that it's easier to read.


Regular Expressions

At this point, we're going to shift gears a little bit and talk briefly about regular expressions. If you're not familiar with regular expressions, just know that they are powerful ways to perform character or string matching. You can read much more about them on Wikipedia.

At some point during your WordPress development career, you're likely going to encounter them - either in the core source code, the code of theme or plugin, or even needing them to perform an action in your own project.

Luckily, PHP offers some really simple, really powerful functions for using regular expressions in your code; however, there are proper and improper uses of them when it comes to working with them in WordPress.

Here are the general rules:

  • Use the preg functions that PHP offers
  • Do not use the \e switch that is offered by PHP - use preg_replace_callback instead.

For those who are curious, there are a number of functions that are available.

For example, I recommend becoming familiar with:

Finally, preg_replace_callback is a way to call a function when a regular expression has found a match.

Obviously, the rules for regular expressions in WordPress are simple - it's more of a matter of knowing the functions that you should use and what you shouldn't use, and how to employ them in your day-to-day work.


PHP Tags

The last thing to cover in this article is the importance of how to use PHP tags in the PHP files that make up your project. Luckily, there is a very simple rule of thumb for this particular situation:

  • Never use shorthand PHP tags

First and foremost, this means that you should never open a file or an inline PHP statement with <? or with <?=. Naturally, all inline PHP statements should still be terminated with the ?> closing tag.

Now, this next topic is a bit of a deviation from the Coding Standards, at least at the time of this writing, it's becoming a more common practice to leave the terminating tag off of the bottom of the file if and only if the first line of the file in question is an opening <?php tag.

Specifically, this is more common in the context of plugins than it is in themes and here's why: PHP is a way in which server side code can be embedded within front-end markup. As such, it requires both an opening tag and closing tag so that the interpreter knows how to parse the code.

But if you're writing a plugin or an application file that's 100% PHP, then there's no need to add a terminating tag at the end of the file. The parser will be able to detect it itself, and if you do include a terminating tag, then you can potentially have whitespace left at the end of the file that can cause all sorts of problems when it comes time to activate the plugin.

So in addition to the coding standard that is defined above, I'd also add:

  • Avoid adding a terminating PHP tag in pure PHP files.

Conclusion

As we close in on the final stretch of examining the WordPress Coding Standards, we'll begin to focus on smaller things such as ternary operators and Yoda conditions; however, we'll also be taking a look at the finer points of performing inline SQL queries and the important rules around that.

If you've not already caught up on the series, now is a good time to read back through what we've covered so far as it will factor into where we're headed with the next set of articles.

Related Posts
  • Code
    Creative Coding
    Using WordPress for Web Application Development: A ReviewApplication foundation 400
    Over the past few months, we've been taking a look at all of the features and aspects that make WordPress a potential foundation for application development. In fact, we've spent roughly 15 articles talking about all that WordPress offers. And though we'll be reviewing each of the points in this email, perhaps the biggest thing to take away that building web applications using WordPress is different than using many of the popular frameworks that are currently available namely because WordPress isn't a framework.Read More…
  • Code
    Theme Development
    Making the Perfect WordPress Theme: How to Code WellWp white 400
    In the previous part of this series; we went through various WordPress APIs that we should learn about, talked about the importance of making a theme translatable (or even better, releasing them already translated into other languages) and understood the concept of licensing themes and using licensed products with the themes. In this article, we're going to focus on code: We'll see how to code with WordPress coding standards, how to properly comment our code and how to validate and test the theme.Read More…
  • Code
    Cheat Sheets
    The WordPress Coding Standards: Bringing It All TogetherThe wordpress coding standards
    When it comes to writing a series of blog posts, one of the most challenging aspects as a reader is actually keeping up with every post that is published. Even if you do manage to try and keep up, posts that are in excess of 1,000 words - especially those that include code - can take time that many of us don't have especially when it comes to juggling our work lives, home lives, hobbies, and other things. So in order to make sure that the information presented throughout this series is still presented in a digestible way, I thought I'd experiment with doing a summary of the entire series. That way, for those of you who have missed an article or haven't had the time to sit down and go through each article, can still get the gist of each point mentioned throughout the articles. With that said, let's take a look at everything we covered when reviewing the WordPress Coding Standards.Read More…
  • Code
    Cheat Sheets
    The WordPress Coding Standards: Indentation, Space Usage, and Trailing SpacesThe wordpress coding standards
    The entire purpose of this series to help expose the WordPress Coding Standards, why they matter, and how to write quality WordPress code. In order to do this, we're taking an in-depth look at each section of the WordPress Coding Standards. So far, we've covered: Naming Conventions and Function Arguments Single Quotes and Double Quotes Today, we're going to be covering the importance of white space. Specifically, we're going to cover indentation, space usage, and trailing spaces. As easy as it sounds, these are several of the most ignored or misused aspects of the codings standards.Read More…
  • Code
    Cheat Sheets
    The WordPress Coding Standards: An IntroductionThe wordpress coding standards
    When it comes to building WordPress-based products, we're somewhat cursed (or blessed, depending on how you see it), with a double-edged sword: Because WordPress is written in PHP, it's relatively easy to get WordPress - or the project itself - to do whatever it is we want to do all the while avoiding best practices. But this raises the question: What's the point of an API or formal coding standards if we're simply going to ignore them? We've written quite a bit about the WordPress APIs in previous articles, and we've touched on the WordPress Coding Standards, but we've never really taken a deep dive into the coding standards, understanding each aspect of them, and why they matter. So in this series, we're going to be doing just that.Read More…
  • Code
    Creative Coding
    A Case for Code Comments: The Server-SideA case for code comments   the server side
    When it comes to writing code, regardless of the language or platform that's being used, we developers tend to be divided on how much or how little we should comment our code. On one hand, there are some who believe that code should be self-documenting. That is, it should be written clear enough such that it doesn't need comments. On the other hand, some believe that everything should be commented. That is, there should be comments for every class, every function, every block, and every line. Then, of course, there are those who fall in the middle. In fact, some developers only comment areas of their code that may be confusing rather than picking the all-or-nothing approach outlined above.Read More…