Coding standards in WordPress development are essential for a strong and sustainable code base. They are guidelines and conventions that developers follow when writing code, helping to enhance collaboration, simplify maintenance, and ensure overall reliability.
In addition, coding standards prevent common pitfalls and errors and improve code quality. In WordPress development, multiple contributors often collaborate on a single project, so coding standards are the foundation for effective teamwork. They facilitate communication, mitigate potential conflicts, and help make the development process more efficient.
![图片[1]-WordPress 编码标准简介-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050707431560.png)
Adherence to coding standards promotes consistency across projects and makes it easier for developers to seamlessly switch between code bases. This consistency extends to the readability and maintainability of code and promotes a common understanding among team members.
The Official WordPress Coding Standards cover five key areas of a cohesive and efficient development process:
- PHP ensures server-side code consistency
- HTML for promoting structured and semantic markup
- JavaScript for effective client-side functionality
- CSS for consistent styling methods
- Ensure that the final product is inclusive and user-friendly accessible to individuals with diverse needs
PHP Standards in WordPress Development
![图片[2]-WordPress 编码标准简介-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050707492237.jpg)
WordPress-specificPHP coding standardsEnsuring consistency and readability of WordPress code, these standards are mandatory for WordPress core and highly recommended for themes and plugins. These standards cover everything from naming conventions to indentation and code structure to improve readability and facilitate collaboration.
The WordPress PHP standards cover the following categories:
- generalized- These standards include: placing the opening and closing PHP tags on a separate line when embedding multi-line PHP snippets in HTML code blocks; avoiding shorthand PHP tags when using single and double quotes; and guidelines for writing include and require statements:
// Opening and closing PHP tags within HTML.
// Put open/close tags on their own lines.
## DO
function foo() {
foo() { >DO function foo() { ?
<div>
<?php
echo esc_html (
bar (
$param1,
$param2
)
);
?>
</div>
<?php
}
## DON'T
if ( $x === $y ) { ?>
<div>
<!-- HTML content -->
<?php }
// Avoid shorthand PHP tags
## DO
## DON'T
// Writing include/require statements.
// Avoid include_once as it continues execution
// even if the file is not found.
// Do not use brackets around the file path.
## DO
require_once ABSPATH . 'file-name.php'
## DON'T
require_once __DIR__ . '/file-name.php'
include_once ( ABSPATH . 'file-name.php' );
christen-Naming standards include naming conventions and interpolation of naming dynamic hooks:
## DO
// Use lowercase letters for function and variable names.
function my_function( $some_variable ) {}
// Use uppercase letters for constant names.
Define('MAX_AGE', 60);
## DON'T
// Use camelCase.
function myFunction( $someVariable ) {}
void- The whitespace standard establishes guidelines for space usage, indentation, and removal of trailing spaces. (To start a lively discussion among developers, just ask them whether they prefer tabs or spaces when indenting code. Regardless of preference, the official recommendation from WordPress developers is to use tabs, and in addition to PHP, this is also true for JavaScript and CSS. (So keep that in mind when working on collaborative projects).
## DO
// Put spaces after commas.
$colors = ['red', 'green', 'blue']
// Put spaces on both sides of the opening and
// closing brackets of control structures.
foreach( $foo as $bar ) { ...
// Defining a function: function my_function() { .
function my_function() { ...
// Logical comparisons: if ( !
if ( ! $foo ) { ...
// Accessing array items: $a = $foo['bar'] { ...
$a = $foo['bar']
$a = $foo[ $bar ]
## DON'T
$colors = ['red','green','blue']
foreach($foo as $bar){ ...
function my_function(){ ...
if (!$foo) { ...
$a = $foo[ 'bar' ]
$a = $foo[$bar]
formatting- Formatting standards for WordPress PHP development include bracket styles, array declarations, guidelines for multi-line function calls, type declarations, magic constants, and expansion operators:
// DO
// Use the following brace style.
If ( condition ) {
action(); } elseif ( condition2 ) {
} elseif ( condition2 ) {
action2(); } elseif ( condition2 ) { action2()
} else {
default_action(); } elseif ( condition2 ) { action2(); } else { default_action()
}
// Declare arrays using the long syntax.
$numbers_long = array(1, 2, 3, 4, 5); // In multi-line function calls, each parameter should only take up one line.
/* In multi-line function calls, each parameter should only take up one line.
Multi-line parameter values should be assigned a variable, and the variable passed to the function call. */
$data = array(
'address' => '123 Main Street, Cityville', );; $data = array(
).
$greeting_message = sprintf(
/* translation function. %s maps to User's name */
__( 'Hello, %s!', 'yourtextdomain' ),
$data['user_name']
);
$result = some_function (
$data,
$greeting_message, $greeting_message, $greeting_message
/* translation function %s maps to city name*/
sprintf( __( 'User resides in %s.' ), 'Cityville' )
);
// Magic constants should be uppercase.
// The ::class constant should be lowercase with no spaces around the scope resolution operator (::).
add_action( my_action, array( __CLASS__, my_method ) ).
add_action( my_action, array( My_Class::class, my_method ) ).
/* Add a space or new line with appropriate
indentation before a spread operator.
There should be.
/* Add a space or new line with appropriate indentation before a spread operator.
No space between the spread operator and the variable/function it applies to.
* No space between the spread and the reference
No space between the spread and the reference operators when combined.
*/No space between the spread and the reference operators when combined.
//DO
function some_func( &. .$arg1 ) {
bar( ... .$arg2 );
bar(
array( ... .$arg3 ), .
... .array_values( $array_vals )
);
}
//DONT
function some_func( & ... $arg1 ) {
bar(...
$arg2 );
bar(
array( ... .$arg3 ),... .array_values( $array_vals )
);
}
Declaration Statements, Namespaces, and Import Statements- These coding standards cover namespace declarations anduse
Statements:
// Each namespace declaration should contain
// capitalized words separated by underscores.
namespace My_CompanyProjectKinsta_ProjectUtilities; namespace My_CompanyProjectKinsta_ProjectUtilities.
// Import use statements can use aliases // to prevent name collisions.
// to prevent name collisions.
use Project_NameFeatureClass_C as Aliased_Class_C; // Import use statements can use aliases // to prevent name collisions.
object-oriented programming (OOP) - These standards include the use of only one object structure per document, the provision of usage characteristics, and the use of a single object structure.use
statements, a guide to ensuring that visibility is always declared, an overview of the order of visibility and modifiers, and an overview of the rules for object instantiation:
// Trait use statements should be at the top of a class.
// Trait use statements should be at the top of a class.
// the first and last statements.
// Always declare visibility.
class Foo {
use Bar_Trait; public $baz = Bar_Trait
public $baz = true; public $baz = true; // Always declare visibility.
...
}
// Always use parentheses when instantiating a new
// object instance.
// Don't add space between a class name and the opening bracket.
$foo = new Foo(); // Don't add space between a class name and the opening bracket.
control structure- The control structure includes using elseif
notelse if
and Yoda Conditional Criteria. Yoda Statement: When mixing variables with constants, literals, or function calls in logical comparisons, place the variables on the right side to prevent accidental assignments, as shown below:
// A "legal" comparison: if ( true === $result ) {
if ( true === $result ) {
// Do something with $result
}
// But a typo like this could get past you: if ( $result = true ) { // Do something with $result }
if ( $result = true ) { // Do something with $result } // But a typo like this could get past you.
// We will always end up here
operator (computing)- These standards cover ternary operators, error control operators ( @
) and increment/decrement operators:
// Always have ternary operators
// test if the statement is true, not false.
$programming_language = ( 'PHP' === $language ) ? 'cool' : 'meh';
// Favor pre-increment/decrement over post-increment/decrement.
// for stand-alone statements.
// DO
-$a; --$a; --$a; --$a.
// DON'T
$a--; // DON'T
- comprehensive database-- Database coding standards provide instructions for executing database queries and formatting SQL statements.
- Other recommendations- Other suggestions include standards such as using self-explanatory flag values for function arguments, clever code, closures (anonymous functions), regular expressions, shell commands, and instructions to avoid
extract()
The
WordPress Inline Documentation Standard for PHP Code
In addition to the above guidelines, WordPress also provides PHP code for theInline Documentation Standards. WordPress uses a custom document architecture that draws its inspiration from the PHPDoc syntax, an evolving standard for creating custom documents forphpDocumentorDocumentation for maintained PHP code. These standards simplify the generation of external documentation and contribute to the broader WordPress developer community by promoting a common understanding of the structure of the code base.
![图片[3]-WordPress 编码标准简介-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050707513324.jpg)
PHP documentation in WordPress is mostly displayed as formatted blocks or inline comments. Document the following in your WordPress files:
- Functions and Class Methods
- Classes
- Class members, including properties and constants
- Requires and contains
- Hooks (operating and filter)
- Inline Comments
- header
- a constant (math.)
HTML and CSS Standards in WordPress
WordPress themes and plugins follow strictHTML coding standards.to ensure consistency, accessibility, and maintainability. The guidelines emphasize semantic markup, encouraging developers to use HTML elements for their intended purpose. This approach enhances content structure and improves search engine optimization (SEO) performance.
The HTML code standard provides guidance on the following:
- Validation - should be based on theW3C ValidatorValidate all HTML pages to ensure that the markup is formatted correctly.
- Self-Closing Element- A forward slash in a self-closing element should be preceded by a space.
<!-- DO -->
<br />
<!-- DON'T –>
<br/>
Attributes and tags -All attributes and tags should be lowercase. In addition, attribute values should be lowercase only when interpreted by a machine. If written for humans, the correct capitalization of headings should be used.
<!-- DO -->
<a href="http://example.com/" title="Link Description">Descriptive text</a>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- DON'T -->
<a href="http://example.com/" title="link description">Click here</a>
quotation mark (punct.)- All attributes must have a value and must use either single or double quotes. Failure to quote these values may result in a security breach.
<!
indent- HTML indentation should always reflect the logical structure. When mixing PHP and HTML, indent PHP blocks to match the surrounding HTML code.
<!-- DO -->
<?php if ( ! have_articles() ) : ?>
<div class="article">
<h1 class="article-title">Not Found</h1>
<div class="article-content">
<p>No results were found.</p>
<?php get_error_msg(); ?>
</div>
</div>
<?php endif; ?>
<!-- DON'T -->
<?php if ( ! have_articles() ) : ?>
<div class="article">
<h1 class="article-title">Not Found</h1>
<div class="article-content">
<p>No results were found.</p>
<?php get_error_msg(); ?>
</div>
</div>
<?php endif; ?>
In addition to these HTML standardsThe WordPress CSS standard alsocan help create clean, modular and responsive stylesheets. They set a baseline for collaboration and review from core code to themes to plugins. These guidelines help ensure that the code is readable, consistent and makes sense.
The WordPress CSS Code Standards emphasize the use of specific classes to position elements to promote a consistent and organized structure. Specifically, they outline the following standards:
framework::
/* DO
Each selector should be on its own line ending with
Each selector should be on its own line ending with a comma or curly brace.
The closing brace should occupy the same indentation level as the opening selector.
The closing brace should occupy the same indentation level as the opening selector.
#selector-2 {
property: value; }
}
picker::
/* DO
Use lowercase and separate words using hyphens.
Use double quotes around values for attribute selectors.
Avoid overqualified selectors, such as div. container. */
#contact-form {
property: value; }
}
input[type="text"] {
property: value; }
}
causality(Ordering and vendor prefixes):
/* Append properties with a colon and a space.
Properties should be lowercase - except font names
snd vendor-specific properties - and use shorthand. */
#selector {
property: value; }
}
fig. values (ethical, cultural etc)::
/* Add a space before the value and a semicolon after.
Use double quotes.
0 values should not have units.
Use a leading zero for decimal values.
Delineate multiple comma-separated values for
Delineate multiple comma-separated values for a single property with a space or new line.
#contact-form {
font-family: "Helvetica Neue", sans-serif; opacity: 0.9; }
box-shadow.
0 0 0 1px #5b9dd9,.
0 0 0 2px 1px rgba(20, 120, 170, 0.9);
}
Media Enquiry::
/* Rules set for media queries should be indented one level in.
Keep media queries grouped by media at the bottom of the stylesheet. */
@media all and (max-width: 1024px) and (min-width: 780px) {
$selector {
property: value; }
}
}
![图片[4]-WordPress 编码标准简介-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050707524050.jpg)
Since its inception in 2003, WordPress' HTML and CSS coding standards have been aligned with the World Wide Web Consortium's (W3C) HTML and CSS guidelines.The W3C standards, which emphasize the integration of responsive design principles and semantic markup, have influenced the development of themes and plugins since the release of HTML5 and CSS3.
Adopting the W3C guidelines ensures that WordPress sites adhere to global web standards, enhances interoperability and the user experience, and reflects a commitment to staying up-to-date, secure, and compatible within the broader web ecosystem.
Adhering to these guidelines in WordPress emphasizes the importance of targeting theW3C HTML Markup ValidatorPerform HTML quality validation.
These HTML and CSS standards ensure that WordPress websites are visually appealing, user-friendly, and efficiently presented across platforms. They support a seamless user experience and facilitate collaboration between developers from different aspects of the WordPress ecosystem.
Link to this article:https://www.361sale.com/en/9377The article is copyrighted and must be reproduced with attribution.
No comments