Over the years I have developed a “TAIT Style”, or a PHP – HTHL Coding Standard, that has helped me make reading code easier. Recently I was on a forum, answering a question about a WordPress Theme, and included a statement that said something like:

[php]<?php if ( $var == ‘something’ ) { ?>[/php]

if ( $var == 'something' ) {

Someone there told me I was “wrong” (can working PHP be wrong?) and it should be in a style with “Yoda Conditions” like:

[php]<?php if ( ‘something’ == $var ) { ?>[/php]

if ( 'something' == $var ) {

I was actually amused, not only does my wife sometimes refer to me as “Yoda” (the wise and powerful Jedi Master), but because “his” statement was actually the way I would normally code it! I had just got in a hurry in an example on that forum. That person directed me to the WordPress Coding Standards (I have included below). I never really considered that WordPress had a coding standard! To my amazement, they were very near my own coding standards (perhaps I should call it the “Tightly Aligned Integrated Technology Style”, T.A.I.T. Style). I haven’t really tried to put TAIT Style on paper before, but it is similar to the WordPress Coding Standards, with a few exceptions…

For those that did not know the term “Yoda Conditions” is post 1980’s. Prior to that, in the late 1960’s and early 1970’s “TAIT-COMS” was used (Tightly Aligned Integrated Technology – Conditions? Considerations? Connectors?)

I am going to stick with my own coding standard (TAIT Style) as I believe it is better, I think WordPress compromised in a couple areas, with people who are seeking to be cute, or take short cuts… Or who just learned one way, and think because they learned it that way, that is logically the best for everyone! I disagree, but not too loudly.

Anyway here are my few exceptions…

Single and Double Quotes

My rule is slightly different, with basically the same meaning. Always use a single quote, unless you need a double quote. That means you need to learn when a single quote won’t work and when you need a double quote.

Brace Style

Braces should always be used except for a single line like this:

[php]if ( condition )

Space Usage

Basically I use one space wherever I can!

Obvious exceptions are before the semicolon “;” at the end of the line, used basically as a period. I do not use a space in the brackets of an empty function. I also do not uses spaces in type casting!

( array ) looks ridiculous to me so I use (array)

No one has a problem with elseif so do not put a space in it!

A place that require no space is before the parenthesis right after the function name.

Ternary Operator

Frankly most people have problems with them so I do not used them. Read the WordPress section “Clever Code” below and let the word “readability” sink in!


No one has a problem with elseif so do not put the space in it!

Cast to array

One other thing I think is likely good policy is to cast to array before foreach.

[php]foreach ( (array) $array as $var ) {[/php] Not this:
[php]foreach ( $array as $var ) {[/php]

If you accidentally pass a var instead of an array this code will still run!

Final Thoughts

Well, that pretty much reflects my coding standard. I have learned that by following these virtually everyone accepts my code!

Here now is the rest of the WordPress Coding Standards…

‘ . “\n\t\t” . ‘‘ . “\n\t” . ‘

‘ . “\n”;
}else{ ?>

WordPress Coding Standards

Some parts of the WordPress code structure for PHP markup are inconsistent in their style. WordPress is working to gradually improve this by helping users maintain a consistent style so the code can become clean and easy to read at a glance.

Keep the following points in mind when writing code for WordPress, whether for core programming code, Plugins, or WordPress Themes. The guidelines are similar to Pear standards in many ways, but differ in some key respects.

See also this post on the wp-hackers list. There is also a page on proposed Inline Documentation standards.



Single and Double Quotes

Use single and double quotes when appropriate. If you’re not evaluating anything in the string, use single quotes. 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>";

An exception to this is JavaScript, which sometimes requires double or single quotes. Text that goes into attributes should be run through esc_attr() so that single or double quotes do not end the attribute value and invalidate the HTML and cause a security issue. See Data Validation for further details.


Your indentation should always reflect logical structure. Use real tabs and not spaces, as this allows the most flexibility across clients.

Exception: if you have a block of code that would be more readable if things aligned, use spaces:

$foo   = 'somevalue';
$foo2  = 'somevalue2';
$foo34 = 'somevalue3';
$foo5  = 'somevalue4';

For associative arrays, values should start on a new line:

$my_array = array(
'foo'   => 'somevalue',
'foo2'  => 'somevalue2',
'foo3'  => 'somevalue3',
'foo34' => 'somevalue3',

Rule of thumb: tabs should be used at the beginning of the line and spaces should be used mid-line.

Brace Style

Braces should be used for multiline blocks in the style shown here:

if ( condition ) {
} elseif ( condition2 && condition3 ) {
} else {

Furthermore, if you have a really long block, consider whether it can be broken into two or more shorter blocks or functions. If you consider such a long block unavoidable, please put a short comment at the end so people can tell at glance what that ending brace ends — typically this is appropriate for a logic block, longer than about 35 rows, but any code that’s not intuitively obvious can be commented.

Single line blocks can omit braces for brevity:

if ( condition )
elseif ( condition2 )

If any related set of blocks is more than one line long then all of the related blocks should be enclosed in braces:

if ( condition ) {
} elseif ( condition2 ) {

Loops should always contain braces as this enhances readability, and allows for fewer line edits for debugging or additional functionality later.

foreach ( $items as $item ) {
    process_item( $item );

include_once vs require_once

Learn the difference between include_once and require_once, and use each as appropriate. To quote the php manual page on include(): “The two constructs are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error.” Fatal errors stop script execution.

Regular Expressions

Perl compatible regular expressions (PCRE, preg_ functions) should be used in preference to their POSIX counterparts. Never use the /e switch, use preg_replace_callback instead.

No Shorthand PHP tags

Important: Never use shorthand PHP start tags. Always use full PHP tags.


<?php ... ?>


<? ... ?>

Remove Trailing Spaces

Important: Make sure you remove trailing whitespace after closing PHP tags.

Also remove trailing spaces at the end of each line of code.

Space Usage

Always put spaces after commas and on both sides of logical and assignment operators.

x == 23
foo && bar
! foo
array( 1, 2, 3 )

Put spaces on both sides of the opening and closing parenthesis of if, elseif, foreach, for and switch blocks.

foreach ( $foo as $bar ) { ...

When defining a function, do it like so:

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

When calling a function, do it like so:

myfunction( $param1, funcparam( $param2 ) );

When performing logical comparisons, do it like so:

if ( ! $foo ) { ...

When type casting, do it like so:

foreach ( (array) $foo as $bar ) { ...

$foo = (boolean) $bar;

Formatting SQL statements

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.

Functions that update the database should expect their parameters to lack SQL slash escaping when passed. Escaping should be done as close to the time of the query as possible, preferably by using $wpdb->prepare()

$wpdb->prepare() is a method that handles escaping, quoting, and int-casting for SQL queries. It uses a subset of the sprintf() style of formatting. Example :

$var = "dangerous'"; // raw data that may or may not need to be escaped
$id = some_foo_number(); // data we expect to be an integer, but we're not certain

$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID = %d", $var, $id ) );

%s is used 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. The benefit of this is that we don’t have to remember to manually use $wpdb->escape(), and also that it is easy to see at a glance whether something has been escaped or not, because it happens right when the query happens.

See Database Data Validation for more information.

Database Queries

Avoid touching the database directly. If there is a defined function that can get the data you need, use it. Database abstraction (using functions instead of queries) helps keep your code forward-compatible and, in cases where results are cached in memory, it can be many times faster. If you must touch the database, get in touch with some developers by posting a message to the wp-hackers mailing list. They may want to consider creating a function for the next WordPress version to cover the functionality you wanted.

Naming Conventions

Use lowercase letters in variable and function names (never camelCase). Separate words via underscores.

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

Class names should use capitalized words separated by underscores. Any acronyms should be all upper case.

class Walker_Category extends Walker { [...] }
class WP_HTTP { [...] }

Files should be named descriptively using lowercase letters. Hyphens should separate words.


Class file names should be based on the class name with class- prepended and the underscores in the class name replaced with hyphens, for example WP_Error becomes:


This file-naming standard is for all current and new files with classes. There is one exception for three files that contain code that got ported into BackPress: class.wp-dependencies.php, class.wp-scripts.php, class.wp-styles.php. Those files are prepended with class., a dot after the word class instead of a hyphen.

Files containing template tags in wp-includes should have -template appended to the end of the name so that they are obvious.


Self-Explanatory Flag Values for Function Arguments

Prefer string values to just true and false when calling functions.

// Incorrect
function eat( $what, $slowly = true ) {
eat( 'mushrooms' );
eat( 'mushrooms', true ); // what does true mean?
eat( 'dogfood', false ); // what does false mean? The opposite of true?

Since PHP doesn’t support named arguments, the values of the flags are meaningless and each time we come across a function call like these above we have to search for the function definition. The code can be made more readable by using descriptive string values, instead of booleans.

// Correct
function eat( $what, $speed = 'slowly' ) {
eat( 'mushrooms' );
eat( 'mushrooms', 'slowly' );
eat( 'dogfood', 'fast' );

Ternary Operator

If you don’t use a variable more than once, don’t create it. This includes queries. Always use the wpdb class of functions when interacting with the database.

Ternary operators are fine, but always have 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.)

For example:

// (if statement is true) ? (do this) : (else, do this);
$musictype = ( 'jazz' == $music ) ? 'cool' : 'blah';
// (if field is not empty ) ? (do this) : (else, do this);

Yoda Conditions

When doing logical comparisons, always put the variable on the right side, like above. If you forget an equal sign it’ll throw a parse error instead of just evaluating true and executing the statement. It really takes no extra time to do, so if this saves one bug it’s worth it.

Clever Code

In general, readability is more important than cleverness or brevity.

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

Although the above line is clever, it takes a while to grok if you’re not familiar with it. So, just write it like this:

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

else if or elseif

Both notations are used in conjunction with curly brackets, there is no rule which to prefer. elseif can save you some hassles sometimes.



All HTML pages should be verified against the W3C validator to ensure that the markup is well formed. This in and of itself is not directly indicative of good code, but it helps to weed out problems that are able to be tested via automation. It is no substitute for manual code review. (For other validators see HTML Validation.)

Self-closing Elements

All tags must be properly closed. For tags that can wrap nodes such as text or other elements, termination is a trivial enough task. For tags that are self-closing, the forward slash should have exactly one space preceding it <br /> vs. the compact but incorrect <br/>. The W3C specifies that a single space should precede the self-closing slash (source).

Attributes and Tags

All tags and attributes must be written in lowercase. Additionally, attribute values should be lowercase when the purpose of the text therein is only to be interpreted by machines. For instances in which the data needs to be human readable, proper title capitalization should be followed, such as:

For machines:

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

For humans:

<a href="http://example.com/" title="Description Goes Here">Example.com</a>


According to the W3C specifications for XHTML, all attributes must have a value, and must use double- or single-quotes (source). The following are examples of proper and improper usage of quotes and attribute/value pairs.


<input type="text" name="email" disabled="disabled" />
<input type='text' name='email' disabled='disabled' />


<input type=text name=email disabled>

In HTML, attributes do not all have to have values, and attribute values do not always have to be quoted. All of the examples above are valid HTML.

However, WordPress uses XHTML (and where HTML5 is used, we use the XHTML serialisation rather than the HTML serialisation). Therefore, the HTML style should never be used.


As with PHP, HTML indentation should always reflect logical structure. Use tabs and not spaces.

When mixing PHP and HTML together, indent PHP blocks to match the surrounding HTML code. Closing PHP blocks should match the same indentation level as the opening block.


<?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(); ?>

<?php endif; ?>


      <?php if ( ! have_posts() ) : ?>
      <div id="post-0" class="post error404 not-found">

         <h1 class="entry-title">Not Found</h1>
         <div class="entry-content">
            <p>Apologies, but no results were found.</p>
<?php get_search_form(); ?>

<?php endif; ?>


Inspiration and Credits