PHP TEAM CODE STANDARDS WORDPRESS & PHP CODING STANDARDS Single and Double Quotes o Use single and double quotes when appropriate. o If you’re not evaluating anything in the string, use single quotes. Not necessary to use escape quotes in a string, because you can just alternate your quoting style using single and double quotes. o An exception to this is JavaScript, which sometimes requires double or single quotes. o Text that goes into attributes should be run through esc_attr() Eg. echo '<a href="/static/link" title="Yeah yeah!">Link name</a>'; echo "<a href='$link' title='$linktitle'>$linkname</a>"; Indentation 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 are aligned, use spaces: Eg. [tab]$foo = 'somevalue'; [tab]$foo2 = 'somevalue2'; [tab]$foo34 = 'somevalue3'; [tab]$foo5 = 'somevalue4'; For associative arrays, values should start on a new line. Note the comma after the last array item: this is recommended because it makes it easier to change the order of the array, and makes for cleaner diffs too. Eg. $my_array = array( [tab]'foo' => 'somevalue', [tab]'foo2' => 'somevalue2', [tab]'foo3' => 'somevalue3', [tab]'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. Eg. if ( condition ) { action1(); action2(); } elseif ( condition2 && condition3 ) { action3(); action4(); VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 1 PHP TEAM CODE STANDARDS } else { defaultaction(); } 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 where 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: Eg. if ( condition ) action1(); elseif ( condition2 ) action2(); else action3(); If any related set of blocks is more than one line long then all of the related blocks should be enclosed in braces: Eg. if ( condition ) { action1(); } elseif ( condition2 ) { action2a(); action2b(); } Loops should always contain braces as this enhances readability, and allows for fewer line edits for debugging or additional functionality later. Eg. foreach ( $items as $item ) { process_item( $item ); } 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. Correct: <?php ... ?> <?php = $var ?> Incorrect: <? ... ?> VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 2 PHP TEAM CODE STANDARDS <?=$var ?> Remove Trailing Spaces Important: If you do not omit the closing PHP tag at the end of a file (which is preferred), make sure you remove trailing whitespace. 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, comparison, string and assignment operators. Eg. x == 23 foo && bar ! foo array( 1, 2, 3 ) $baz . '-5' $term .= 'X' Put spaces on both sides of the opening and closing parenthesis of if, elseif, foreach, for, and switch blocks. Eg. foreach ( $foo as $bar ) { ... When defining a function, do it like so: Eg. function my_function( $param1 = 'foo', $param2 = 'bar' ) { ... When calling a function, do it like so: Eg. my_function( $param1, func_param( $param2 ) ); When performing logical comparisons, do it like so: Eg. if ( ! $foo ) { ... When type casting, do it like so: Eg. foreach ( (array) $foo as $bar ) { ... $foo = (boolean) $bar; When referring to array items, only include a space around the index if it is a variable, for example: Eg. $x = $foo['bar']; // correct $x = $foo[ 'bar' ]; // incorrect $x = $foo[0]; // correct $x = $foo[ 0 ]; // incorrect $x = $foo[ $bar ]; // correct $x = $foo[$bar]; // incorrect Formatting SQL Statements When formatting SQL statements you may break it into several lines and indent if it is sufficiently complex to warrant it. Always capitalize the SQL parts of the statement like UPDATE or WHERE. Functions that update the database should have 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. $wpdb->prepare() will take care of escaping and quoting VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 3 PHP TEAM CODE STANDARDS Eg. $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 ) ); Manual escaping can be done by , $wpdb->escape(). 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, where results are cached in memory, it can be many times faster. Naming Conventions Use lowercase letters in variable, action, and function names (never camelCase). Separate words via underscores. Don’t abbreviate variable names un-necessarily; let the code be unambiguous and selfdocumenting. Eg. function some_name( $some_variable ) { [...] } Class names should use capitalized words separated by underscores. Any acronyms should be all upper case. Eg. class Walker_Category extends Walker { [...] } class WP_HTTP { [...] } Files should be named descriptively using lowercase letters. Hyphens should separate words. Eg. my-plugin-name.php 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: Eg. class-wp-error.php Files containing template tags in wp-includes should have -template appended to the end of the name so that they are obvious. Eg. general-template.php Self-Explanatory Flag Values for Function Arguments Prefer string values to just true and false when calling functions. Eg. // Incorrect function eat( $what, $slowly = true ) { ... } eat( 'mushrooms' ); eat( 'mushrooms', false ); // what does false mean? VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 4 PHP TEAM CODE STANDARDS Since PHP doesn’t support named arguments, the values of the flags are meaningless, and each time we come across a function call like the examples above, we have to search for the function definition. The code can be made more readable by using descriptive string values, instead of booleans. Eg. // Correct function eat( $what, $speed = 'slowly' ) { ... } eat( 'mushrooms' ); eat( 'dogfood', 'fast' ); Ternary Operator Ternary operators are fine, but always have them test if the statement is true, not false. Otherwise, it just gets confusing. Eg. // (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 Eg. if ( true == $the_force ) { $victorious = you_will( $be ); } When doing logical comparisons, always put the variable on the right side, constants or literals on the left. In the above example, if you omit an equals sign , you’ll get a parse error, because you can’t assign to a constant like true. If the statement were the other way around ( $the_force = true ), the assignment would be perfectly valid, returning 1, causing the if statement to evaluate to true, and you could be chasing that bug for a while. Clever Code In general, readability is more important than cleverness or brevity. Eg. 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: Eg. if ( ! isset( $var ) ) $var = some_function(); VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 5 PHP TEAM CODE STANDARDS HTML CODING STANDARDS Validation All HTML pages should be verified against the W3C validator to ensure that the markup is well formed. URL : http://validator.w3.org/ 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: Eg. <br /> The W3C specifies that a single space should precede the self-closing slash Attributes and Tags All tags and attributes must be written in lowercase. Attribute values should be lowercase when the purpose of the text therein is only to be interpreted by machines. If the data needs to be human readable, proper title capitalization should be followed. Eg. For machines: <meta http-equiv="content-type" content="text/html; charset=utf-8" /> For humans: <a href="http://example.com/" title="Description Here">Example.com</a> Quotes According to the W3C specifications for XHTML, all attributes must have a value, and must use double- or singlequotes Eg. Correct: <input type="text" name="email" disabled="disabled" /> <input type='text' name='email' disabled='disabled' /> Incorrect: <input type=text name=email disabled> Indentation 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. Eg. Correct: <?php if ( ! have_posts() ) : ?> <div id="post-1" class="post"> <h1 class="entry-title">Not Found</h1> <div class="entry-content"> VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 6 PHP TEAM CODE STANDARDS <p>Apologies, but no results were found.</p> <?php get_search_form(); ?> </div> </div> <?php endif; ?> Incorrect: <?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(); ?> </div> </div> <?php endif; ?> VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 7 PHP TEAM CODE STANDARDS CSS CODING STANDARDS Structure Use tabs, not spaces, to indent each property. Add two blank lines between sections and one blank line between blocks in a section. Each selector should be on its own line, ending in either a comma or an opening curly brace. Property-value pairs should be on their own line, with one tab of indentation and an ending semicolon. The closing brace should be flush left, using the same level of indentation as the opening selector. Eg. Correct: #selector-1, #selector-2, #selector-3 { background: #fff; color: #000; } Incorrect: #selector-1, #selector-2, #selector-3 { background: #fff; color: #000; } #selector-1 { background: #fff; color: #000; } Selectors Use lowercase and separate words with hyphens when naming selectors. Avoid camelcase and underscores. Use human readable selectors that describe what element(s) they style. Attribute selectors should use double quotes around values. Refrain from using over-qualified selectors, div.container can simply be stated as .container Eg. Correct: #comment-form { margin: 1em 0; } input[type="text"] { line-height: 1.1; } Incorrect: #commentForm { /* Avoid camelcase. */ margin: 0; } #comment_form { /* Avoid underscores. */ VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 8 PHP TEAM CODE STANDARDS margin: 0; } div#comment_form { /* Avoid over-qualification. */ margin: 0; } #c1-xr { /* What is a c1-xr?! Use a better name. */ margin: 0; } input[type=text] { /* Should be [type="text"] */ line-height: 110% /* Also doubly incorrect */ } Properties Properties should be followed by a colon and a space. All properties and values should be lowercase, except for font names and vendor-specific properties. Use hex code for colors, or rgba() if opacity is needed. Avoid RGB format and uppercase, and shorten values when possible: #fff instead of #FFFFFF. Use shorthand (except when overriding styles) for background, border, font, list-style, margin, and padding values as much as possible. (For a shorthand reference, see CSS Shorthand.). Property Ordering Property orders Display Positioning Box model Colors and Typography Other Top/Right/Bottom/Left (TRBL/trouble) – should be used in margins,padding Corner specifiers (e.g. border-radius-*-*) should be top-left, top-right, bottom-right, bottom-left. Vendor Prefixes Vendor prefixes should go longest (-webkit-) to shortest (unprefixed). Values should be right aligned with spaces after the colon provided that all the values are the same across all prefixes. Eg. .koop-shiny { -webkit-box-shadow: inset 0 0 1px 1px #eee; -moz-box-shadow: inset 0 0 1px 1px #eee; } Values Space before the value, after the colon. VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 9 PHP TEAM CODE STANDARDS Do not pad parentheses with spaces Always end in a semicolon Use double quotes rather than single quotes, and only when needed, such as when a font name has a space. 0 values should not have units unless necessary, such as with transition-duration. Line height should also be unit-less, unless necessary to be defined as a specific pixel value. Use a leading zero for decimal values, including in rgba(). Multiple comma-separated values for one property should be separated by either a space or a newline, including within rgba(). Newlines should be used for lengthier multi-part values such as those for shorthand properties like box-shadow and text-shadow. Each subsequent value after the first should then be on a new line, indented to the same level as the selector and then spaced over to left-align with the previous value. Correct: .class { /* Correct usage of quotes */ background-image: url(images/bg.png); font-family: "Helvetica Neue", sans-serif; } .class { /* Correct usage of zero values */ font-family: Georgia, serif; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.5), 0 1px 0 #fff; } Media Queries Media queries allow us to gracefully degrade the DOM for different screen sizes. If you are adding any, be sure to test above and below the break-point you are targeting. It is generally advisable to keep media queries grouped by media at the bottom of the stylesheet. An exception is made for the wp-admin.css file in core, as it is very large and each section essentially represents a stylesheet of its own. Media queries are therefore added at the bottom of sections as applicable. Rule sets for media queries should be indented one level in. \ Example: @media all and (max-width: 699px) and (min-width: 520px) { /* Your selectors */ } Commenting Commenting sections and subsections For sections and subsections: /** * #.# Section title * * Description of section, whether or not it has media queries, etc. */ .selector { float: left; VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 10 PHP TEAM CODE STANDARDS } For inline: /* This is a comment about this selector */ .another-selector { position: absolute; top: 0 !important; /* I should explain why this is so !important */ } Best Practices If you are attempting to fix an issue, attempt to remove code before adding more. Magic Numbers are unlucky. These are numbers that are used as quick fixes on a one-off basis. Example: .box { margin-top: 37px }. DOM will change over time, target the element you want to use as opposed to “finding it” through its parents. Example: Use .highlight on the element as opposed to .highlight a (where the selector is on the parent) Know when to use the height property. It should be used when you are including outside elements (such as images). Otherwise use line-height for more flexibility. Do not restate default property & value combinations (for instance display: block; on block-level elements). VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 11 PHP TEAM CODE STANDARDS JAVASCRIPT CODING STANDARDS Braces Braces should be used for multiline blocks. Rule of thumb: Opening brace should be on the same line as the function definition, the conditional, or the loop. Closing brace should be on the line directly following the last statement of the block. Quotations Single quotes are preferred over double quotes, for the sake of simplicity; however, double quotes should be used when appropriate. Whitespace Use spaces liberally throughout your code. Proper spacing drastically improves the legibility of any line of code. Indentation Use tabs, not spaces, as this allows the most flexibility across clients. Many wars have been fought over the use of tabs versus spaces. We use real tabs in WordPress core – please respect that. Always put spaces on both sides of the opening and closing parenthesis of if, else if, for, forin, do, while<, and switch blocks. Rule of thumb: Tabs should be used at the beginning of the line, and spaces should be used mid-line. Trailing Whitespace Remove any whitespace from blank lines. Whitespace can also easily accumulate at the end of a line – avoid this where possible. One way of catching whitespace buildup is to enable visible whitespace characters within your text editor. This should be done prior to minification. Naming Conventions Name functions and variables using camelCase, not underscores. Constructors Name constructors with TitleCase. Eg. var myVariable = 5, MyConstructor = function() { this.attr = 'example'; }; Filenames Separate words in files using hyphens. Include both an uncompressed version with the format file-name.js, and a compressed version using the format filename.min.js. The var Keyword Each function should begin with a single comma-delimited var statement that declares any local variables necessary. If a function does not declare a variable using var, it will be assigned to the current context (which is frequently the global scope, and worst scenario), and can unwittingly refer to and modify that data. Assignments within the var statement should be listed on individual lines. While declarations can be grouped on a single line. Any additional lines should be indented with an additional tab. Eg. var i, j, length, value = 'WordPress'; Objects and functions that occupy more than a handful of lines should be assigned after the var statement. VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 12 PHP TEAM CODE STANDARDS Operators Surround operators with spaces in order to properly show the order of operations: Eg. var i; i = ( 20 + 30 ) - 17; Objects Create objects with curly bracket notation, and not new Object() notation. When declaring objects, place a space after the colon, but not before. Similarly, in var statements and objects, place a space after the comma, but not before. When declaring an object with more than one key, it is advisable to give each key its own line. var a = { key: 'value' }, b, c; b={ key1: 'value1', key2: 'value2' }; Never end an object with a comma. Internet Explorer violently rejects trailing commas and trailing commas are not valid ECMAScript. a={ key1: 'value', key2: 'value' // A comma here would cause IE to implode. }; jQuery There are a number of different ways to resolve conflicts with jQuery and other plugins. Unfortunately, there’s no consistent way in which this is done, which ultimately results in one plugin breaking another plugin because the jQuery function isn’t properly relinquished. To avoid this, define an anonymous function, and pass jQuery as the argument before doing anything else: (function ($) { // ... }(jQuery)); This will negate the need to call noConflict or to set the $ using another variable. VERSATILE SOFT SOLUTIONS http://versatile-soft.com Page 13