WordPress Coding Standards

Article Tools

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 are 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:

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.

Indentation

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

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.

Remove Trailing Spaces

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

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 :

Previous postWordPress Deprecated Functions Hook Next postFinding Your CSS Styles

Related Posts

Comments are closed.