Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Coding standards help avoid common coding errors, improve the readability of code, and simplify
modification. They ensure that files within the project appear as if they were created by a single
person.
Following the standards means anyone will be able to understand a section of code and modify it, if
needed, without regard to when it was written or by whom.
HTML
Validation
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.
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:
1
<br />
<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.
For machines:
1
For humans:
1
Page 1 of 22
Quotes
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.
Correct:
1
2
Incorrect:
1
In HTML, attributes do not all have to have values, and attribute values do not always have to be
quoted. While all of the examples above are valid HTML, failing to quote attributes can lead to
security vulnerabilities. Always quote attributes.
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.
Correct:
1
2
3
4
5
6
7
8
9
Incorrect:
1
2
3
Page 2 of 22
4
5
6
7
8
9
<div class="entry-content">
<p>Apologies, but no results were found.</p>
<?php get_search_form(); ?>
</div>
</div>
<?php endif; ?>
CSS
Like any coding standard, the purpose of the CSS Coding Standards is to create a baseline for
collaboration and review within various aspects of the project, from core code to themes to plugins.
Files within a project should appear as though created by a single entity. Above all else, create code
that is readable, meaningful, consistent, and beautiful.
Within core stylesheets, inconsistencies will often be found. We are working on addressing these and
make every effort to have patches and commits from this point forward follow the CSS coding
standards. More information on the above and contributing to UI/front-end development will be
forthcoming in a separate set of guidelines.
Structure
There are plenty of different methods for structuring a stylesheet. With the CSS in core, it is important
to retain a high degree of legibility. This enables subsequent contributors to have a clear
understanding of the flow of the document.
#selector-1,
#selector-2,
#selector-3 {
Page 3 of 22
4
5
6
background: #fff;
color: #000;
}
Incorrect:
1
2
3
4
5
6
Selectors
With specificity, comes great responsibility. Broad selectors allow us to be efficient, yet can have
adverse consequences if not tested. Location-specific selectors can save us time, but will quickly lead
to a cluttered stylesheet. Exercise your best judgement to create selectors that find the right balance
between contributing to the overall style and layout of the DOM.
Similar to the Standards for file names, 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
Correct:
1
2
3
4
5
6
7
#comment-form {
margin: 1em 0;
}
input[type="text"] {
line-height: 1.1;
}
Incorrect:
1
2
3
4
5
Page 4 of 22
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
Similar to selectors, properties that are too specific will hinder the flexibility of the design. Less is
more. Make sure you are not repeating styling or introducing fixed dimensions (when a fluid solution
is more acceptable).
Property Ordering
Group like properties together, especially if you have a lot of them.
Nacin
Above all else, choose something that is meaningful to you and semantic in some way. Random
ordering is chaos, not poetry. Our choice is logical or grouped ordering, wherein properties are
grouped by meaning and ordered specifically within those groups. The properties within groups are
also strategically ordered to create transitions between sections, such as background directly before
color. The baseline for ordering is:
Display
Positioning
Page 5 of 22
Box model
Colors and Typography
Other
Things that are not yet used in core itself, such as CSS3 animations, may not have a prescribed place
above but likely would fit into one of the above in a logical manner. Just as CSS is evolving, so our
standards will evolve with it.
Top/Right/Bottom/Left (TRBL/trouble) should be the order for any relevant properties (e.g. margin),
much as the order goes in values. Corner specifiers (e.g. border-radius-*-*) should be top-left, topright, bottom-right, bottom-left. This is derived from how shorthand values would be ordered.
Example:
1
2
3
4
5
6
7
#overlay {
position: absolute;
z-index: 1;
padding: 10px;
background: #fff;
color: #777;
}
Example:
1
2
3
4
5
6
7
#overlay {
background: #fff;
color: #777;
padding: 10px;
position: absolute;
z-index: 1;
}
Vendor Prefixes
We use grunt-autoprefixer as a pre-commit tool to easily manage necessary browser prefixes, thus
making the majority of this section moot. For those interested in following that output without using
Grunt, vendor prefixes should go longest (-webkit-) to shortest (unprefixed). All other spacing remains
as per the rest of standards.
1
2
3
4
5
.sample-output {
-webkit-box-shadow: inset 0 0 1px 1px #eee;
-moz-box-shadow: inset 0 0 1px 1px #eee;
box-shadow: inset 0 0 1px 1px #eee;
}
Page 6 of 22
Values
There are numerous ways to input values for properties. Follow the guidelines below to help us retain
a high degree of consistency.
Correct:
1
2
3
4
5
6
7
8
9
10
Incorrect:
1
2
3
4
5
6
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:
1
2
3
4
Commenting
Comment, and comment liberally. If there are concerns about file size, utilize minified files and the
SCRIPT_DEBUG constant. Long comments should manually break the line length at 80 characters.
A table of contents should be utilized for longer stylesheets, especially those that are highly
sectioned. Using an index number (1.0, 1.1, 2.0, etc.) aids in searching and jumping to a location.
Comments should be formatted much as PHPDoc is. The CSSDoc standard is not necessarily widely
accepted or used but some aspects of it may be adopted over time. Section/subsection headers
should have newlines before and after. Inline comments should not have empty newlines
separating the comment from the item to which it relates.
/**
* #.# Section title
*
* Description of section, whether or not it has media queries, etc.
*/
.selector {
float: left;
Page 8 of 22
For inline:
1
2
3
4
5
6
Best Practices
Stylesheets tend to get long in length. Focus slowly gets lost whilst intended goals start repeating and
overlapping. Writing smart code from the outset helps us retain the overview whilst remaining
flexible throughout change.
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).
Page 9 of 22
The JavaScript Coding Standards are adapted from the jQuery JavaScript Style Guide. Our standard
differs from the jQuery guidelines in the following ways:
Code Refactoring
Code refactoring should not be done just because we can. Lead Developer Andrew Nacin
Many parts of the code structure for JavaScript are inconsistent in their style. So we need to be
refactoring it as code evolves.
While the coding standards are important, refactoring older .js files simply to conform to the
standards is not an urgent issue. Whitespace-only patches for older files are strongly discouraged.
All new or updated JavaScript code should be reviewed to ensure it conforms to the standards, and
passes JSHint.
Spacing
Use spaces liberally throughout your code. When in doubt, space it out.
These rules encourage liberal spacing for improved developer readability. The minification process
creates a file that is optimized for browsers to read and process.
// Preferred
var map = {
ready: 9,
when: 4,
'you are': 15
};
// Acceptable for small objects
var map = { ready: 9, when: 4, 'you are': 15 };
// Bad
var map = { ready: 9,
when: 4, 'you are': 15 };
array = [ a, b ];
Page 11 of 22
3
4
5
6
7
8
9
foo( arg );
foo( 'string', object );
foo( options, object[ property ] );
foo( node, 'property', 2 );
Exceptions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// For consistency with our PHP standards, do not include a space around
// string literals or integers used as key values in array notation:
prop = object['default'];
firstArrayElement = arr[0];
// Function with a callback, object, or array as the sole argument:
// No space on either side of the argument
foo(function() {
// Do stuff
});
foo({
a: 'alpha',
b: 'beta'
});
foo([
'alpha',
'beta'
]);
// Function with a callback, object, or array as the first argument:
// No space before the first argument
foo(function() {
// Do stuff
}, options );
// Function with a callback, object, or array as the last argument:
// No space after after the last argument
foo( data, function() {
// Do stuff
});
Page 12 of 22
var i;
if ( condition ) {
doSomething( 'with a string' );
} else if ( otherCondition ) {
otherThing({
key: value,
otherKey: otherValue
});
} else {
somethingElse( true );
}
// This is also done to conform to our PHP standards.
while ( ! condition ) {
iterating++;
}
for ( i = 0; i < 100; i++ ) {
object[ array[ i ] ] = someFn( i );
$( '.container' ).val( array[ i ] );
}
try {
// Expressions
} catch ( e ) {
// Expressions
}
Semicolons
Use them. Never rely on Automatic Semicolon Insertion (ASI).
Page 13 of 22
(function( $ ) {
// Expressions indented
function doSomething() {
// Expressions indented
}
})( jQuery );
var a, b, c;
if ( myFunction() ) {
// Expressions
} else if ( ( a && b ) || c ) {
// Expressions
} else {
// Expressions
}
Multi-line Statements
When a statement is too long to fit on one line, line breaks must occur after an operator.
1
2
3
4
5
6
// Bad
var html = '<p>The sum of ' + a + ' and ' + b + ' plus ' + c
+ ' is ' + ( a + b + c );
// Good
var html = '<p>The sum of ' + a + ' and ' + b + ' plus ' + c +
Page 14 of 22
' is ' + ( a + b + c );
Lines should be broken into logical groups if it improves readability, such as splitting each expression
of a ternary operator onto its own line, even if both will fit on a single line.
1
2
3
4
5
6
7
// Acceptable
var baz = ( true === conditionalStatement() ) ? 'thing 1' : 'thing 2';
// Better
var baz = firstCondition( foo ) && secondCondition( bar ) ?
qux( foo, bar ) :
foo;
When a conditional is too long to fit on one line, successive lines must be indented one extra level to
distinguish them from the body.
1
2
3
4
elements
.addClass( 'foo' )
.children()
.html( 'hello' )
.end()
.appendTo( 'body' );
outer scope (which is frequently the global scope, a worst-case 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. Objects and
functions that occupy more than a handful of lines should be assigned outside of the var statement,
to avoid over-indentation.
1
2
3
4
5
6
7
8
9
10
11
// Good
var k, m, length,
// Indent subsequent lines by one tab
value = 'Sweet Ride';
// Bad
var foo = true;
var bar = false;
var a;
var b;
var c;
Globals
All globals used within a file should be documented at the top of that file. Multiple globals can be
comma-separated.
This example would make passwordStrength an allowed global variable within that file:
1
/* global passwordStrength:true */
The true after passwordStrength means that this global is being defined within this file. If you are
accessing a global which is defined elsewhere, omit :true to designate the global as read-only.
Common Libraries
Backbone, jQuery, Underscore, and the global wp object are all registered as allowed globals in the
root .jshintrc file.
Backbone and Underscore may be accessed directly at any time. jQuery should be accessed
through $ by passing thejQuery object into an anonymous function:
1
2
3
(function( $ ) {
// Expressions
})( jQuery );
Page 16 of 22
This will negate the need to call .noConflict(), or to set $ using another variable.
Files which add to, or modify, the wp object must safely access the global to avoid overwriting
previously set properties:
1
2
// At the top of the file, set "wp" to its existing value (if present)
window.wp = window.wp || {};
Naming Conventions
Variable and function names should be full words, using camel case with a lowercase first letter.
Constructors intended for use with new should have a capital first letter (UpperCamelCase).
Names should be descriptive, but not excessively so. Exceptions are allowed for iterators, such as the
use of i to represent the index in a loop.
Comments
Comments come before the code to which they refer, and should always be preceded by a blank line.
Capitalize the first letter of the comment, and include a period at the end when writing full sentences.
There must be a single space between the comment token (//) and the comment text.
Single line comments:
1
2
3
4
someStatement();
// Explanation of something complex on the next line
$( 'p' ).doSomething();
/*
This is a comment that is long enough to warrant being stretched
over the span of multiple lines.
*/
Inline comments are allowed as an exception when used to annotate special arguments in formal
parameter lists:
1
2
3
Page 17 of 22
Equality
Strict equality checks (===) must be used in favor of abstract equality checks (==). The only exception
is when checking for both undefined and null by way of null.
1
2
3
4
// Check for both undefined and null values, for some important reason.
if ( undefOrNull == null ) {
// Expressions
}
Type Checks
These are the preferred ways of checking the type of an object:
Strings
Use single-quotes for string literals:
1
Page 18 of 22
When a string contains single quotes, they need to be escaped with a backslash (\):
1
2
Switch Statements
The usage of switch statements is generally discouraged, but can be useful when there are a large
number of cases especially when multiple cases can be handled by the same block, or fall-through
logic (the default case) can be leveraged.
When using switch statements:
Use a break for each case other than default. When allowing statements to fall through, note that
explicitly.
Indent case statements one tab within the switch.
1
2
3
4
5
6
7
8
9
10
11
12
13
switch ( event.keyCode ) {
// ENTER and SPACE both trigger x()
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
x();
break;
case $.ui.keyCode.ESCAPE:
y();
break;
default:
z();
}
It is not recommended to return a value from within a switch statement: use the case blocks to set
values, then returnthose values at the end.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
result = 'exit';
break;
default:
result = 'default';
}
return result;
}
Best Practices
Arrays
Creating arrays in JavaScript should be done using the shorthand [] constructor rather than the new
Array() notation.
1
Object literal notation should be used unless the object requires a specific prototype, in which case
the object should be created by calling a constructor function with new.
1
Object properties should be accessed via dot notation, unless the key is a variable, a reserved word,
or a string that would not be a valid identifier:
1
2
3
4
prop = object.propertyName;
prop = object[ variableKey ];
prop = object['default'];
prop = object['key-with-hyphens'];
Page 20 of 22
Yoda Conditions
Whenever you are comparing an object to a string, boolean, integer, or other constant or literal, the
variable should always be put on the right hand side, and the constant or literal put on the left.
1
2
3
Iteration
When iterating over a large collection using a for loop, it is recommended to store the loops max
value as a variable rather than re-computing the maximum every time:
1
2
3
4
5
6
7
8
9
10
11
12
13
var obj = {
first: 'thing 1',
second: 'thing 2',
Page 21 of 22
4
5
6
7
8
9
10
11
12
13
14
15
third: 'lox'
};
var arr = _.chain( obj )
.keys()
.map(function( key ) {
return key + ' comes ' + obj[ key ];
})
// Exit the chain
.value();
// arr === [ 'first comes thing 1', 'second comes thing 2', 'third comes lox' ]
Never use jQuery to iterate over raw data or vanilla JavaScript objects.
Page 22 of 22