
WordPress 開發中的編碼標準對於一個強大和可持續的程式碼庫至關重要。它們是開發人員在編寫程式碼時遵守的準則和慣例,有助於加強協作、簡化維護並確保整體可靠性。
此外,編碼標準還能防止常見的陷阱和錯誤,提高程式碼質量。在 WordPress 開發中,多個貢獻者通常會在一個專案上進行協作,因此編碼標準是有效團隊協作的基礎。它們促進了溝通,緩解了潛在衝突,並有助於提高開發流程的效率。
遵守編碼標準可促進各專案之間的一致性,使您更容易在不同的程式碼庫之間無縫切換。這種一致性可擴充套件到程式碼的可讀性和可維護性,並促進團隊成員之間的共同理解。
WordPress 官方編碼標準涵蓋了五個關鍵領域,以確保開發過程的一致性和高效性:
- 確保伺服器端程式碼一致性的 PHP
- 促進結構化和語義標記的 HTML
- JavaScript 用於實現有效的客戶端功能
- CSS 用於保持風格一致
- 可訪問性,確保最終產品對有不同需求的個人具有包容性和使用者友好性
在本文中,我們將探討 WordPress 這些編碼標準,以幫助您開始構建符合標準的網站,併為 WordPress 開發社羣做出貢獻。
WordPress 開發中的 PHP 標準
WordPress 專用的 PHP 編碼標準可確保 WordPress 程式碼的一致性和可讀性。它們是 WordPress Core 的強制性標準,也是主題和外掛的強烈推薦標準。這些標準涵蓋各個方面,包括命名規則、縮排和程式碼結構,以提高可讀性和便於協作。
WordPress PHP 標準分為以下幾類:
常規 – 這些標準包括在 HTML 程式碼塊中嵌入多行 PHP 程式碼片段時,將開頭和結尾的 PHP 標記放在一行中,使用單引號和雙引號時避免使用速記 PHP 標記,以及 include
和 require
語句的編寫指南:
// Opening and closing PHP tags within HTML:
// Put open/close tags on their own lines.
// Opening and closing PHP tags within HTML:
// Put open/close tags on their own lines.
## DO
function foo() {
?>
<div>
<?php
echo esc_html (
bar (
$param1,
$param2
)
);
?>
</div>
<?php
}
## DON'T
if ( $x === $y ) { ?>
<div>
<!-- HTML content -->
<?php }
// Opening and closing PHP tags within HTML:
// Put open/close tags on their own lines.
## 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
// Avoid shorthand PHP tags
## DO
<?php ... ?>
<?php esc_html( $x ); ?>
## DON'T
<? ... ?>
<? esc_html( $x ); ?>
// Avoid shorthand PHP tags
## DO
<?php ... ?>
<?php esc_html( $x ); ?>
## DON'T
<? ... ?>
<? esc_html( $x ); ?>
// 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.
require_once ABSPATH . 'file-name.php'
require_once __DIR__ . '/file-name.php'
include_once ( ABSPATH . 'file-name.php' );
// 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' );
// 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' );
命名 – 命名標準包括命名約定和動態鉤子的插值命名:
// Use lowercase letters for function and variable names.
function my_function( $some_variable ) {}
// Use uppercase letters for constant names.
function myFunction( $someVariable ) {}
## 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 ) {}
## 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 ) {}
空白字元 – 空白字元標準規定了空格使用、縮排和刪除尾部空格的準則。(如果你想在開發人員中掀起一場熱烈的討論,只需問問他們在縮排程式碼時更喜歡製表符還是空格即可。無論您的偏好如何,WordPress 開發人員的官方建議都是使用製表符,除了 PHP 之外,JavaScript 和 CSS 也是如此。因此,在合作專案中,請記住這一點)。
// 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 ) { ...
function my_function() { ...
// Accessing array items:
$colors = ['red','green','blue']
foreach($foo as $bar){ ...
function my_function(){ ...
## 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() { ...
// Logical comparisons:
if ( ! $foo ) { ...
// Accessing array items:
$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]
## 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() { ...
// Logical comparisons:
if ( ! $foo ) { ...
// Accessing array items:
$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]
格式化 – WordPress PHP 開發的格式化標準包括括號樣式、陣列宣告、多行函式呼叫指南、型別宣告、神奇常量和展開運算子:
// Use the following brace style.
} elseif ( condition2 ) {
// 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.
Multi-line parameter values should be assigned a variable, and the variable passed to the function call. */
'user_name' => 'John Doe',
'email' => 'john@example.com',
'address' => '123 Main Street, Cityville',
$greeting_message = sprintf(
/* translation function. %s maps to User's name */
__( 'Hello, %s!', 'yourtextdomain' ),
$result = some_function (
/* 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.
* No space between the spread operator and the
variable/function it applies to.
* No space between the spread and the reference
function some_func( &...$arg1 ) {
...array_values( $array_vals )
function some_func( & ... $arg1 ) {
array( ...$arg3 ),...array_values( $array_vals )
// DO
// Use the following brace style.
if ( condition ) {
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.
Multi-line parameter values should be assigned a variable, and the variable passed to the function call. */
$data = array(
'user_name' => 'John Doe',
'email' => 'john@example.com',
'address' => '123 Main Street, Cityville',
);
$greeting_message = sprintf(
/* translation function. %s maps to User's name */
__( 'Hello, %s!', 'yourtextdomain' ),
$data['user_name']
);
$result = some_function (
$data,
$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:
* No space between the spread operator and the
variable/function it applies to.
* 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 )
);
}
// DO
// Use the following brace style.
if ( condition ) {
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.
Multi-line parameter values should be assigned a variable, and the variable passed to the function call. */
$data = array(
'user_name' => 'John Doe',
'email' => 'john@example.com',
'address' => '123 Main Street, Cityville',
);
$greeting_message = sprintf(
/* translation function. %s maps to User's name */
__( 'Hello, %s!', 'yourtextdomain' ),
$data['user_name']
);
$result = some_function (
$data,
$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:
* No space between the spread operator and the
variable/function it applies to.
* 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 )
);
}
宣告語句、名稱空間和匯入語句 – 這些編碼標準包括名稱空間宣告和 use
語句:
// Each namespace declaration should contain
// capitalized words separated by underscores.
namespace My_CompanyProjectKinsta_ProjectUtilities;
// Import use statements can use aliases
// to prevent name collisions.
use Project_NameFeatureClass_C as Aliased_Class_C;
// Each namespace declaration should contain
// capitalized words separated by underscores.
namespace My_CompanyProjectKinsta_ProjectUtilities;
// Import use statements can use aliases
// to prevent name collisions.
use Project_NameFeatureClass_C as Aliased_Class_C;
// Each namespace declaration should contain
// capitalized words separated by underscores.
namespace My_CompanyProjectKinsta_ProjectUtilities;
// Import use statements can use aliases
// to prevent name collisions.
use Project_NameFeatureClass_C as Aliased_Class_C;
物件導向程式設計(OOP)– 這些標準包括每個檔案只使用一個物件結構,提供使用特質 use
語句的指導,確保始終宣告可見性,概述可見性和修飾符的順序,以及概述物件例項化的規則:
// Trait use statements should be at the top of a class.
// Trait use should have at least one line before and after
// the first and last statements.
// Always declare visibility.
// Always use parentheses when instantiating a new
// Don't add space between a class name and the opening bracket.
// Trait use statements should be at the top of a class.
// Trait use should have at least one line before and after
// the first and last statements.
// Always declare visibility.
class Foo {
use Bar_Trait;
public $baz = true;
...
}
// Always use parentheses when instantiating a new
// object instance.
// Don't add space between a class name and the opening bracket.
$foo = new Foo();
// Trait use statements should be at the top of a class.
// Trait use should have at least one line before and after
// the first and last statements.
// Always declare visibility.
class Foo {
use Bar_Trait;
public $baz = true;
...
}
// Always use parentheses when instantiating a new
// object instance.
// Don't add space between a class name and the opening bracket.
$foo = new Foo();
控制結構 – 控制結構包括使用 elseif
、not else if
以及 Yoda 條件準則: 在邏輯比較中將變數與常量、字面量或函式呼叫混合時,應將變數放在右側,以防止意外賦值,如下所示:
if ( true === $result ) {
// Do something with $result
// But a typo like this could get past you:
// We will always end up here
// A "legal" comparison:
if ( true === $result ) {
// Do something with $result
}
// But a typo like this could get past you:
if ( $result = true ) {
// We will always end up here
}
// A "legal" comparison:
if ( true === $result ) {
// Do something with $result
}
// But a typo like this could get past you:
if ( $result = true ) {
// We will always end up here
}
運算子 – 這些標準包括三元運算子、錯誤控制運算子 ( @
) 和增/減運算子:
// 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.
// 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;
// DON'T
$a--;
// 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;
// DON'T
$a--;
資料庫 – 資料庫編碼標準提供了執行資料庫查詢和格式化 SQL 語句的說明。
其他建議 – 其他建議包括為函式引數使用不言自明的標誌值、巧妙程式碼、閉包(匿名函式)、正規表示式、shell 命令以及避免使用 extract()
的說明等標準。
WordPress PHP 程式碼的內聯文件標準
除上述指南外,WordPress還為PHP程式碼提供了內聯文件標準。WordPress 使用定製的文件模式,該模式從 PHPDoc 語法中汲取靈感,PHPDoc 是由 phpDocumentor 維護的一個不斷髮展的為 PHP 程式碼提供文件的標準。這些標準簡化了外部文件的生成,並通過促進對程式碼庫結構的共同理解,為更廣泛的 WordPress 開發者社羣做出了貢獻。
WordPress 中的 PHP 文件大多以格式化塊或內聯註釋的形式出現。在 WordPress 檔案中記錄以下內容:
- 函式和類方法
- 類
- 類成員,包括屬性和常量
- 要求和包含
- 鉤子(動作和過濾器)
- 內聯註釋
- 檔案頭
- 常量
WordPress 中的 HTML 和 CSS 標準
WordPress 主題和外掛遵守嚴格的 HTML 編碼標準,以確保一致性、可訪問性和可維護性。指南強調語義標記,鼓勵開發人員將 HTML 元素用於其預期目的。這種做法可以增強內容結構,提高搜尋引擎優化 (SEO) 效能。此外,我們還鼓勵您驗證 HTML,以保證跨瀏覽器的相容性。
HTML 程式碼標準為以下方面提供了指導:
驗證 – 您應根據 W3C 驗證器驗證所有 HTML 頁面,以確保您的標記格式良好。
自閉合元素 – 自閉合元素中的正斜槓前應留一個空格。
<!-- DO -->
<br />
<!-- DON'T –>
<br/>
<!-- DO -->
<br />
<!-- DON'T –>
<br/>
屬性和標記 – 所有屬性和標記都應小寫。此外,屬性值只有在機器解釋時才應小寫。如果是為人類編寫,則應使用正確的標題大寫。
<a href="http://example.com/" title="Link Description">Descriptive text</a>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<a HREF="http://example.com/" TITLE="link description">Click here</a>
<!-- 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>
<!-- 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>
引號 – 所有屬性都必須有一個值,並且必須使用單引號或雙引號。不使用引號可能會導致安全漏洞。
<input type="text" name="email" disabled="disabled" />
<input type='text' name='email' disabled='disabled' />
<input type=text name=email disabled>
<!-- DO -->
<input type="text" name="email" disabled="disabled" />
<input type='text' name='email' disabled='disabled' />
<!-- DON'T -->
<input type=text name=email disabled>
<!-- DO -->
<input type="text" name="email" disabled="disabled" />
<input type='text' name='email' disabled='disabled' />
<!-- DON'T -->
<input type=text name=email disabled>
縮排 – HTML 縮排應始終反映邏輯結構。混合使用 PHP 和 HTML 時,PHP 程式碼塊的縮排應與周圍的 HTML 程式碼一致。
<?php if ( ! have_articles() ) : ?>
<h1 class="article-title">Not Found</h1>
<div class="article-content">
<p>No results were found.</p>
<?php get_error_msg(); ?>
<?php if ( ! have_articles() ) : ?>
<h1 class="article-title">Not Found</h1>
<div class="article-content">
<p>No results were found.</p>
<?php get_error_msg(); ?>
<!-- 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; ?>
<!-- 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; ?>
除了這些 HTML 標準外,WordPress 的 CSS 標準還可以幫助您建立簡潔、模組化和響應式的樣式表。它們為從核心程式碼到主題再到外掛的協作和審查設定了基準。這些準則有助於確保程式碼的可讀性、一致性和意義。
WordPress CSS 程式碼標準強調使用特定的類來定位元素,從而促進結構的一致性和條理性。具體來說,這些標準包括:
結構
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. */
/* DO
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. */
#selector-1,
#selector-2 {
property: value;
}
/* DO
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. */
#selector-1,
#selector-2 {
property: value;
}
選擇器
Use lowercase and separate words using hyphens.
Use double quotes around values for attribute selectors.
Avoid overqualified selectors, such as div.container. */
/* 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;
}
/* 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;
}
屬性(排序和瀏覽器引擎字首)
/* Append properties with a colon and a space.
Properties should be lowercase — except font names
snd vendor-specific properties — and use shorthand. */
/* 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;
}
/* 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;
}
值
/* Add a space before the value and a semicolon after.
0 values should not have units.
Use a leading zero for decimal values.
Delineate multiple comma-separated values for
a single property with a space or new line. */
font-family: "Helvetica Neue", sans-serif;
0 0 2px 1px rgba(20, 120, 170, 0.9);
/* 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
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 2px 1px rgba(20, 120, 170, 0.9);
}
/* 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
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 2px 1px rgba(20, 120, 170, 0.9);
}
媒體查詢
/* 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) {
/* 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;
}
}
/* 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;
}
}
註釋
自 2003 年誕生以來,WordPress的HTML和CSS編碼標準一直與全球資訊網聯盟(W3C)的 HTML 和 CSS 指南保持一致。W3C 標準強調整合響應式設計原則和語義標記,從釋出 HTML5 和 CSS3 開始,就對主題和外掛的開發產生了影響。
採用 W3C 準則可確保 WordPress 網站遵守全球網路標準,增強互操作性和使用者體驗,並反映出在更廣泛的網路生態系統中保持最新、安全和相容的承諾。
WordPress 對這些準則的遵守強調了根據 W3C HTML 標記驗證器進行 HTML 質量驗證。
這些 HTML 和 CSS 標準可確保 WordPress 網站在跨平臺時具有視覺吸引力、使用者友好和高效的表現形式。它們支援無縫的使用者體驗,並促進了 WordPress 生態系統不同方面的開發人員之間的協作。
WordPress 中的 JavaScript 編碼標準
WordPress 的編碼標準還為主題和外掛的 JavaScript 程式碼的格式和樣式提供了指導。此外,這些標準還有助於促進程式碼與核心 PHP、HTML 和 CSS 程式碼的一致性。
WordPress JavaScript 編碼標準建立在 jQuery JavaScript 樣式指南的基礎上,該指南於 2012 年推出,是一套全面的編碼規範,可增強程式碼的一致性和可讀性。該指南最初專門針對j Query 專案,但它的成功促使 jQuery 框架以外的專案也廣泛採用該指南。
雖然jQuery指南為WordPress標準提供了參考,但在WordPress開發中也有一些明顯的不同之處:
- WordPress對字串宣告使用單引號。
- 在開關塊中,大小寫語句是縮排的。
- 函式內容採用一致的縮排,包括全檔案閉包。
- 為了與 PHP WordPress 標準保持一致,一些空白規則也有所不同,比如使用製表符或縮排。
- jQuery 的 100 個字元硬行限制雖然值得鼓勵,但並未嚴格執行。
WordPress JavaScript 編碼標準涵蓋以下方面:
- 程式碼重構。
- 程式碼間距,包括物件宣告、陣列和函式呼叫:
// Arrays and function calls
// Include extra spaces around elements and arguments.
// Object declarations
// DO
var obj = {
name: 'John',
age: 27,
height: 179
}
// DON'T
var obj = {
name: 'John', age: 27,
height: 179
}
// Arrays and function calls
// Include extra spaces around elements and arguments.
array = [ 1, 2 ];
foo( arg1, arg2 );
// Object declarations
// DO
var obj = {
name: 'John',
age: 27,
height: 179
}
// DON'T
var obj = {
name: 'John', age: 27,
height: 179
}
// Arrays and function calls
// Include extra spaces around elements and arguments.
array = [ 1, 2 ];
foo( arg1, arg2 );
// Always use semicolons
array = [ 1, 2 ];
// Always use semicolons
array = [ 1, 2 ];
- 縮排和換行,包括塊和大括號、多行語句和鏈式方法呼叫:
// Use tabs for indentation
// if, else, for, while, and try blocks should span multiple lines
} else if ( ( condition && condition ) || condition ) {
// Line breaks must occur after an operator if the statement
// is too long to fit on one line.
var html = '<p>The sum of ' + a + ' and ' + b + ' plus ' + c +
' is ' + ( a + b + c ) + '</p>';
/* If a chain of method calls is too long to fit on a single line,
use one call per line. The first call should be on a separate line from
the object on which the methods are called. */
// Use tabs for indentation
( function ( $ ) {
// Expressions indented
function doSomething() {
// Expressions indented
}
} )( jQuery );
// if, else, for, while, and try blocks should span multiple lines
if ( condition ) {
// Expressions
} else if ( ( condition && condition ) || condition ) {
// Expressions
} else {
// Expressions
}
// Line breaks must occur after an operator if the statement
// is too long to fit on one line.
var html = '<p>The sum of ' + a + ' and ' + b + ' plus ' + c +
' is ' + ( a + b + c ) + '</p>';
/* If a chain of method calls is too long to fit on a single line,
use one call per line. The first call should be on a separate line from
the object on which the methods are called. */
elements
.addClass( 'foo' )
.children()
.html( 'hello' )
.end()
.appendTo( 'body' );
// Use tabs for indentation
( function ( $ ) {
// Expressions indented
function doSomething() {
// Expressions indented
}
} )( jQuery );
// if, else, for, while, and try blocks should span multiple lines
if ( condition ) {
// Expressions
} else if ( ( condition && condition ) || condition ) {
// Expressions
} else {
// Expressions
}
// Line breaks must occur after an operator if the statement
// is too long to fit on one line.
var html = '<p>The sum of ' + a + ' and ' + b + ' plus ' + c +
' is ' + ( a + b + c ) + '</p>';
/* If a chain of method calls is too long to fit on a single line,
use one call per line. The first call should be on a separate line from
the object on which the methods are called. */
elements
.addClass( 'foo' )
.children()
.html( 'hello' )
.end()
.appendTo( 'body' );
- 賦值和全域性,包括用
const
和 let
宣告變數、用 var
宣告變數、全域性和常用庫。
- 命名約定,如縮寫和首字母縮略詞、類定義和常量:
// Abbreviations must be written in camelCase.
// All letters of acronyms should be capitalized.
const currentDOMDocument = window.document;
// Class definition must use UpperCamelCaseConvention.
// Constants should use SCREAMING_SNAKE_CASE convention.
const SESSION_DURATION = 60
// Abbreviations must be written in camelCase.
// All letters of acronyms should be capitalized.
const userId = 1;
const currentDOMDocument = window.document;
// Class definition must use UpperCamelCaseConvention.
class Human {
...
}
// Constants should use SCREAMING_SNAKE_CASE convention.
const SESSION_DURATION = 60
// Abbreviations must be written in camelCase.
// All letters of acronyms should be capitalized.
const userId = 1;
const currentDOMDocument = window.document;
// Class definition must use UpperCamelCaseConvention.
class Human {
...
}
// Constants should use SCREAMING_SNAKE_CASE convention.
const SESSION_DURATION = 60
// Use strict equality/inequality checks (=== and !==)
// instead of abstract checks (== and !=).
if ( result !== false ) {
if !( result === false ) {
// Use strict equality/inequality checks (=== and !==)
// instead of abstract checks (== and !=).
if ( name === "John" ) {
...
}
if ( result !== false ) {
...
}
// Also, with negation:
if !( result === false ) {
...
}
// Use strict equality/inequality checks (=== and !==)
// instead of abstract checks (== and !=).
if ( name === "John" ) {
...
}
if ( result !== false ) {
...
}
// Also, with negation:
if !( result === false ) {
...
}
// Use single-quotes for string literals.
var myString = 'Hello world!'
// Use single-quotes for string literals.
var myString = 'Hello world!'
// Use single-quotes for string literals.
var myString = 'Hello world!'
// Use a break for each case other than default.
// Indent case statements one tab within the switch.
switch ( event.keyCode ) {
// ENTER and SPACE both trigger x()
case $.ui.keyCode.ESCAPE:
// Use a break for each case other than default.
// Indent case statements one tab within the switch.
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();
}
// Use a break for each case other than default.
// Indent case statements one tab within the switch.
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();
}
此外,WordPress 編碼標準還概述了編寫 JavaScript 程式碼的幾種最佳實踐。
與 PHP 一樣,WordPress 也為 JavaScript 程式碼提供了內聯文件標準。這些內聯標準既可以是格式化的文件塊,也可以是內聯註釋,它們遵循 JSDoc 3 內聯 JavaScript 文件標準。內聯標準涵蓋函式、類方法、物件、閉包、物件屬性、事件和檔案頭。
如何確保 WordPress 開發的可訪問性
可訪問性標準對於確保數字內容(包括在 WordPress 等平臺上建立的網站)適合各種能力的人使用至關重要。採用 W3C 的可訪問性標準可確保使用 WordPress 建立的網站具有包容性並可供殘障人士訪問。
W3C 可訪問性指南,特別是《Web Content Accessibility Guidelines》(WCAG),為提高網頁內容的可訪問性提供了一個全面的框架。認識到包容性的重要性,WordPress 已將這些指南納入其核心功能。
例如,WCAG 根據《歐洲無障礙法案》來衡量合規性,該法案將從 2025 年 6 月起適用於歐盟的許多組織。
要滿足不同的需求,就需要實施一些功能和設計原則,如螢幕閱讀器相容性、鍵盤導航和非文字內容的文字替代。
確保 WordPress 的可訪問性不僅僅是一個合規性問題。這是為每個人提供平等獲取資訊和服務機會的承諾。通過遵守 W3C 準則,WordPress 網站變得更易於訪問和使用者友好,從而營造一個更具包容性的網路環境。
在主題和外掛中實施可訪問性功能的一些實際例子包括以下內容:
- 使用語義 HTML – 確保正確使用語義 HTML 標記。例如,在導航選單中使用
<nav>
,在網站頁頭中使用 <header>
,在主要內容中使用 <main>
。這些標籤有助於螢幕閱讀器和其他輔助技術理解頁面結構。
- 為影象、視訊和音訊內容新增文字替代 – 為影象提供描述性的
alt
文字,以便向無法看到影象的使用者傳達其含義。在 WordPress 中,新增圖片時在媒體庫中新增描述性的 alt 屬性。為視訊新增字幕和文字說明,併為音訊內容提供文字替代,以確保耳聾或聽力障礙的使用者能夠獲取資訊。
- 在構建時考慮響應式設計 – 確保您的主題或外掛具有響應性,能很好地適應不同的螢幕尺寸。這種方法有利於使用各種裝置的使用者,並確保跨平臺的一致體驗。
- 設計無障礙表單 – 為表單欄位提供清晰的標籤和說明。使用適當的輸入型別,如電子郵件或電話,以便在移動裝置和輔助技術上觸發正確的鍵盤。
- 使用鍵盤導航 – 確保所有互動元素都可使用鍵盤導航。使用者應能在連結、按鈕和表單欄位中使用選項卡。測試並增強鍵盤的無障礙性,避免只依賴滑鼠進行互動。
有許多程式碼嗅探工具可以幫助您遵守上述平臺編碼標準。讓我們回顧一下您可以用來檢查 WordPress 編碼標準的幾種驗證工具。
PHP_CodeSniffer
PHP_CodeSniffer 會掃描您的 PHP 程式碼庫,以識別與既定規範的偏差。它能精確定位違規編碼和風格差異,使程式碼更簡潔、更高效。這將提高 WordPress 網站的效能,並確保與未來的更新和外掛無縫相容。
W3 Org 的 CSS 驗證服務
W3 Org 的 CSS 驗證服務可掃描 CSS 樣式表,識別並糾正可能妨礙網站最佳效能的潛在錯誤。它在保持一致性和遵守 W3C 標準方面發揮著至關重要的作用,保證了使用者在各種裝置上的流暢體驗。因此,網站的載入時間得到改善,並符合 WordPress 規定的嚴格 CSS 編碼標準。
JSHint
JSHint 可分析 JavaScript 程式碼,識別潛在錯誤、風格不一致之處以及是否符合最佳實踐。它能幫助您編寫更簡潔、更高效的程式碼,最終優化網站效能。它非常注重 WordPress 的編碼標準,確保 JavaScript 程式碼與 WordPress 的整體架構無縫整合,幫助您維護一個連貫、標準化的編碼環境。
WebAIM Contrast Checker
WebAIM 的對比度檢查器可幫助您評估和改進 WordPress 網站的可訪問性。該工具簡化了實現最佳色彩對比以提高可訪問性的複雜過程。利用對比度檢查器的實時反饋,您可以找出需要改進的地方,提高所有訪問者的文字可讀性和可讀性。
小結
編碼標準是高效協同軟體開發的支柱。它們能確保程式碼的一致性和可讀性,簡化編碼過程,提高可維護性,並促進團隊合作。對於 WordPress 開發人員來說,遵守編碼標準對於建立強大、可擴充套件的網站至關重要。
評論留言