Coding Style Guidelines

Some legacy parts of the WordPress code are inconsistent in their style, and our goal is to gradually improve this as we work through all of the code. By keeping a consistent style and following certain guidelinks the code can remain clean and easy to read at a glance. Here is a collection of points you should keep in mind when coding for WordPress. There is no particular order at present. This is very similar to Pear standards in many ways, but differs in some key respects.

Single and double quotes should be used when appropiate. If you're not evaluating anything in the string, use single quotes. You should almost never have to escape HTML quotes in a string, because you can just alternate your quoting style, like so:

echo "<a href='$link' title='$linktitle'>$linkname</a>";
echo '<a href="/static/link" title="Yeah yeah!">Link name</a>';

The only exception to this is JavaScript, which sometimes requires double or single quotes.

Text that goes into attributes should be run through Texturize or an escaping function so that single or double quotes do not end the attribute value and invalidate the XHTML.

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

Brace style is (I believe) K&R. An example from the Pear site:

if ((condition1) || (condition2)) {
    action1;
} elseif ((condition3) && (condition4)) {
    action2;
} else {
   defaultaction;
} // end blah

Furthermore if you have a really long block put a short comment at the end so people can tell at glance what that ending brace ends. Don't clutter the code though, only do this if the logic block is longer than about 35 rows.

Perl compatible regular expressions (PCRE, preg_ functions) should be used in preference to their POSIX counterparts.

Never use shorthand PHP start tags, always use <?php ... ?>.

Always put spaces after commas and on both sides of logical operators, like =, ==, !=, etc.

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 SQLy parts of the statement.

If you don't use a variable more than once, don't create it. This includes queries.

Always use the $wpdb ezSQL functions when interacting with the database.

Ternary operators are fine, but always have them test for true, not false. Otherwise it just gets confusing. Good example:

$musictype = ('jazz' == $music) ? 'cool' : 'blah';

Another important point in the above example, 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.