Quick Summary

  • WordPress coding standards help to improve code-quality, collaboration, and reduce errors.
  • PHP coding standards cover multiple languages used in WordPress: HTML, CSS, and JavaScript.
  • Key practices include proper indentation, naming conventions, consistent structure, and avoiding bad patterns.
  • Tools like code sniffers and validators (e.g., PHP_CodeSniffer) help automatically enforce these standards and improve code quality.

WordPress is a popular online platform for building and managing websites. Just like other platforms, it also has coding standards. Because it’s an open-source platform, many developers are working on it. 

It’s interesting to note that just about 42.4% to 43.4% of the world’s websites are using WP at present. With so many developers working on the platform, it has established guidelines for developers and contributors who want to work on its code. 

WordPress development coding standards are crucial not only for a robust but also a sustainable codebase. The standards serve as guidelines and conventions that developers follow when writing code to simplify maintenance, boost collaboration, and ensure overall reliability. Furthermore, these WordPress code standards safeguard against common errors and pitfalls, improving quality.

Elite logo

Want to Hire a WordPress Development Company?

Browse our Top 10+ WordPress Development Companies in USA.

Why do WordPress Developers Need Coding Standards?

Why are coding standards important for a WordPress development company? Well, every programming language has its coding rules and regulations. 

The only purpose of the WP coding standards is to create a collaborative base and review across the different aspects of the platform’s open-source project and community, from the core to themes and plugins. 

The following are some reasons why developers should use WordPress development coding standards, most of which boil down to the factors below. 

  • It defines the expected look of the code for any developer who touches it. 
  • Provides guardrails for both new and experienced developers to ensure they format their code correctly when introducing or maintaining current features. 
  • Maintains readability in the long run.
  • In the long run, it appears that the same developer wrote all the code. 

In general, it improves a project’s maintainability, which is what it is supposed to do.

WordPress Coding Standards

HTML Coding Standards

HTML Coding Standards

Wrong codes are not a problem; they can be cleaned out. But the cleaning can cost heavily and takes time. Thus, the HTML code should be verified at the W3C validator to flush out the problems tested in automation.

Indentation

This is used to show the start of a paragraph or block. In WordPress, Indentation can be done through ‘tabs’ or ‘two spaces.’ On excellent code, using tabs proves beneficial.

This can also help when combining the flag of PHP and HTML. Tabs can shoot up the readability of the code very high.

This practice always lands a WordPress Developer in a logical structure. One thing to keep in mind while matching PHP and HTML is that closing PHP blocks should reach the level of indentation of the opening blocks.

Correct:

InCorrect:

Quotes

Any attribute must be mandatorily quoted, at least for XHTML.

Quotes are chained with single and double quotes, handling both string and non-string values.

A single quote can be used for a non-string value, whereas a double quote can be used for a string value.

Quoting can diminish security vulnerabilities.

Correct:

InCorrect:

Self-closing Element

All the tags must be closed efficiently. If forgotten, it may fail to work the code. Do not always rely on self-closing tags; the forward slash should be exactly before one space.

Correct:

InCorrect:

Attributes and Tags

All attributes and tags must be written in lowercase. Using uppercase at preferred locations will improve readability for humans. In contrast, the machine will cipher the tags in lowercase.

For Human:

For Machine:

CSS Coding Standards

CSS Coding Standards

CSS coding is all about readability, meaningful code, and a consistent and beautiful framework. The program should appear as a single entity, even though it is coded by multiple users. Sometimes there seem to be inconsistencies in the stylesheet made by the frontend developer.

Structure

There are numerous ways to structure the stylesheet. However, inconsistencies may be present in the core WordPress CSS code. This must be eliminated, and proper CSS coding standards may be followed. A clear understanding of the flow is the main idea behind all these standards.

Use tabs and not spaces to indent.

Two blank lines must be inserted in one section, and one blank line must be used between blocks.

The selector must be in its line ending in a comma or an open curly bracket.

Property value pair must be in line with one tab indentation and ending in a hyphen.

The closing bracket must be pushed to the left with the same indentation as an open selector.

Correct:

InCorrect:

Selector

Efficiency will rise while using a broad selector. Though good code, if not tested, will create issues.

The location-specific stylesheet will save time, but will lead to cluttered stylesheets. Selectors should be such that it contributes to the Document Object Model’s overall style and development (DOM).
Some of the practices are:

Like PHP coding, the lowercase should be used separately by a hyphen.

Avoid camelcase and underscore.

Use a human-readable selector that best describes the element style. Use a double-quoted attribute selector around values.

div. The container can be easily explained as .container and thus neglects a qualified selector.

Correct:

InCorrect:

Properties

Selecting and managing appropriate properties will bring down the size of the code. Too much styling will also create issues with the flexibility of the program.

The code should be flexible and adaptable, adhering to WordPress coding best practices. Here are some key guidelines a WordPress developer should follow:

  1. Followed by a colon and a space
  2. Font name and vendor-specific properties should be represented in uppercase
  3. Hex Code should be used for colors, and if necessary, rgba() can be used for opacity
  4. Avoid RGB format and upper case.
  5. Shorten the value, like #FFFFFF becomes #fff
  6. Use shorthand for non-overriding styles like margin, padding values, font, size, etc.
  7. When the repo is expansive, every bit and byte counts

Correct:

InCorrect:

Properties Ordering

Properties can be grouped by ordering into meaningful groups. It can be grouped so that transitions can be created between sections, like the background before the color.

Creating a baseline such as: Display, Positioning, Box model, Color, Typography, and Other.

Sometimes, some properties may not be in the core. But it can be placed in any of the categories listed above. E.g., CSS3 animation.

Margin can be placed and ordered as (TRBL) top, right, bottom, left. Corner specifiers should be TL, TR, BR, and BL.

Correct:

InCorrect:

Vendor Prefix

Autoprefixer manages browser prefixes, making the section doubtful. Without Grunt, the longest (-WebKit-) can become the shortest (unprefixed).

Code:

Commenting

Commenting is a good practice often accepted by coders.

This will help other coders gain a clearer, faster understanding of the complex codes. Commenting should be liberal.

Comments are allowed up to 80 characters to help maintain file size. Make Use of minified files and the script_DEBUG constant.

Provide a table of contents for longer stylesheets, especially those that are highly sectioned. Use index numbers (1.0, 1.1, 1.2, etc) to search and jump to locations.

As such, whenever possible, use the format as PHPDoc. Sections and subsections should have a new line before and after.

Don’t leave newlines empty between the inline comments.

Value

There are multiple ways to input values for your properties.

  1. Use space before the value
  2. Ending in a semicolon
  3. Using double quotes
  4. 0 values should not have units.

Correct:

InCorrect:

JavaScript Coding Standards

JavaScript Coding Standards

Code Refactoring

Older .js files satisfy the coding standards. “Whitespace-only” patches are not acceptable now

Spacing is indeed a good practice. It improves the readability of code. Indentation should be used with tabs. No whitespaces must be allowed.

Blocks will reside on multiple lines using braces. Having trailing whitespaces at the end is considered an error in .jsHint

For short objects and arrays, they could be delivered as a single line, while represented as one object per line if they are too long.

A good spacing example may be:

Indentation and Line Break

As discussed above, this will improve the code’s readability. In Fact, for any closure, use a tab for indentation.

Blocks and Brackets

If, else, for, while, and try must use braces and can be represented in multiple lines.

The opening brace should be in the same line as the condition or loop, while the closing bracket should be in the consecutive line.

Multiline Statement

If the block is too long, a line break should occur after an operator.

The break should be applied such that it retains logical meaning.

If too long, each operand of the logical operator in a Boolean expression must appear on its own line.

Chained Method Calls

If the code is too long, there should be one call per line following the first call in a separate line.

If the tactic changes context, an extra indentation is required.

Declaring Variables

For code ES2015, const or let ought to be employed in place of var. If a value is assigned, allow should be used or const if the value is not reassigned.

If a function does not start with var, it can lead to the outer scope. Assignments in var should be listed in individual lines.

Global

Earlier, there was heavy use of globals, since now JavaScript is used within plugins, WordPress has lowered the Use of globals.

All the documented globals should be on top.

Valid after password strength suggests that global is being outlined. If you omit true, this can convert it into read-only.

Common Libraries

Backbone, jQuery, Underscore, and global WordPress are registered in the root .jshintrc file.

Backbone and underscore are readily available.

jQuery ought to be accessed through $, bypassing the jQuery object in an anonymous function.

Add to or modify the file should safely access the global for overwriting previously set.

Iteration

While using the ‘for’ loop, store the loop’s maximum value as a variable instead of re-computing the maximum every time.

PHP Coding Standards

PHP Coding Standards

Formatting SQL Statement

Functions that update the database should expect their parameters to lack SQL slash escaping by using $wpdb—-prepare()

String placeholders use %s

%d, which is used for integer placeholders.

Naming Conventions

Only lowercase must be used. Classname should be capitalized along with Acronym separated by an underscore.

Constants should be represented as upper case and underscore for spaces. Files have to be named descriptively and separated by hyphens for space.

Files containing template tags must include -a template appended to the end of the name so that they are apparent.

Clever Code

Besides creating clever code, it should be highly readable. Unless necessary, the loose comparison mustn’t be used as their behavior may be dishonest.

Correct:

InCorrect:

Assignments might not be placed in a conditional.

It’s okay to own multiple empty cases that fall flat on a typical block in switch statements.

If a case contains a block, then it falls through the following partnership.

No Shorthand PHP Tags

Always use full PHP tags

Correct:

InCorrect:

Remove Trailing Spaces

If you’re employing a tag, check that you’re removing the whitespaces at the tip.

Trailing edge whitespaces prevail at the tip of every line of code. Removing it will improve secret writing observation.

Multiline Functional Calls

Multifunction must be in a new line every time. Single or inline comments can take their own line.

Interpolation

Dynamic hooks are best named using interpolation instead of concatenation. Variables used in hook tags should be written in curly brackets with the outer tag name between double quotes.

Yoda Conditions

Put all the variables on the right side and rest everything on the left side. If there are no variables, the order will not be crucial. Yoda conditions for =, <,>,<=, >= are all difficult to read, and so they are avoided.

Tools for Adhering to WordPress Coding Standards

When it comes to WordPress coding standards, there are fortunately numerous code-sniffing tools that help developers. The following are some of the validation tools developers can use. 

PHP_CodeSniffer

This tool scans the PHP codebase to determine deviations from the established norms. Moreover, PHP_CodeSniffer facilitates more efficient, cleaner code by identifying coding infractions as well as style discrepancies. This leads to improved performance of a WordPress website and ensures seamless compatibility with future plugins and updates. 

Benefits:

  • A comprehensive tool that helps detect violations of predefined coding standards.
  • It has an additional tool that can automatically correct violations. 
  • It ensures the code is well written.

W3 Org’s CSS Validation Service

It’s a tool that scans CSS style sheets to identify and correct potential errors that could hinder optimal website performance. It plays a vital role in adhering to the W3C standards and maintaining consistency, guaranteeing a smooth user experience across different devices. 

Benefits:

  • Can speed up and streamline web development because it is easier to learn and use than other CSS frameworks. 
  • Extends the website’s life expectancy.
  • Ensures compatibility across different browsers. 
  • Boosts load speed in most instances. 

WebAIM Contrast Checker

The tool helps assess and improve the WordPress website’s accessibility. Moreover, it simplifies the usually complex process of achieving optimal color contrast for more accessibility. With the tool’s real-time feedback, you can determine areas to improve the legibility and readability of the text for all visitors. 

Benefits

  • Presents the contrast difference between two colors, helping you identify a color that meets the contrast level desired. 
  • Prevents contrast-related accessibility problems early in the design process.

JSHint

The JSHint tool analyzes the JavaScript code, identifying possible errors, inconsistencies in styles, and adherence to best practices. Furthermore, it helps write more efficient and cleaner code that ultimately optimizes the performance of the WordPress website. 

The keen focus of the tool on WP coding standards ensures that the JS code integrates seamlessly with the overall WordPress architecture, helping maintain a standardized and cohesive coding environment.

Conclusion

The goal of any online business these days is not only focused on profitability. To succeed in the highly competitive digital world, your brand should also be able to deliver customer requirements quickly. Thus, optimizing a WordPress website’s speed is an absolute must to gain a competitive edge.