WordPress 編碼標準簡介

WordPress 開發(fā)中的編碼標準對于一個強大和可持續(xù)的代碼庫至關(guān)重要。它們是開發(fā)人員在編寫代碼時遵守的準則和慣例,有助于加強協(xié)作、簡化維護并確保整體可靠性。

此外,編碼標準還能防止常見的陷阱和錯誤,提高代碼質(zhì)量。在 WordPress 開發(fā)中,多個貢獻者通常會在一個項目上進行合作,因此編碼標準是有效團隊協(xié)作的基礎(chǔ)。它們促進了溝通,緩解了潛在沖突,并有助于提高開發(fā)流程的效率。

圖片[1]-WordPress 編碼標準簡介-光子波動網(wǎng) | 專業(yè)WordPress修復服務,全球范圍,快速響應

遵守編碼標準可促進各項目之間的一致性,使開發(fā)人員更容易在不同的代碼庫之間無縫切換。這種一致性可擴展到代碼的可讀性和可維護性,并促進團隊成員之間的共同理解。

官方 WordPress 編碼標準涵蓋了凝聚力和高效開發(fā)過程的五個關(guān)鍵領(lǐng)域:

  • PHP確保服務器端代碼一致性
  • 用于促進結(jié)構(gòu)化和語義標記的HTML
  • JavaScript實現(xiàn)有效的客戶端功能
  • 用于保持一致的樣式方法的CSS
  • 確保最終產(chǎn)品對具有不同需求的個人具有包容性和用戶友好性的可訪問性

WordPress 開發(fā)中的 PHP 標準

圖片[2]-WordPress 編碼標準簡介-光子波動網(wǎng) | 專業(yè)WordPress修復服務,全球范圍,快速響應

WordPress 專用PHP 編碼標準可確保 WordPress 代碼的一致性和可讀性。WordPress 核心必須使用這些標準,主題和插件則強烈推薦使用這些標準。這些標準涵蓋各個方面,包括命名規(guī)則、縮進和代碼結(jié)構(gòu),以提高可讀性和便于協(xié)作。

WordPress PHP 標準涵蓋以下類別:

  • 一般性— 這些標準包括:在 HTML 代碼塊中嵌入多行 PHP 代碼段時,將開頭和結(jié)尾的 PHP 標記單獨放在一行中;使用單引號和雙引號時避免使用速記 PHP 標記;以及編寫 include 和 require 語句的指導原則:
// 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

## 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.

## DO
require_once ABSPATH . 'file-name.php'

## DON'T
require_once  __DIR__ . '/file-name.php'
include_once  ( ABSPATH . 'file-name.php' );

命名—命名標準包括命名約定和命名動態(tài)鉤子的插值:

## 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 ) {}

空白— 空白標準規(guī)定了空格使用、縮進和刪除尾部空格的準則。(如果想在開發(fā)人員中掀起一場熱烈的討論,只需問問他們在縮進代碼時更喜歡制表符還是空格即可。無論喜好如何,WordPress 開發(fā)人員的官方建議都是使用制表符,除了 PHP 之外,JavaScript 和 CSS 也是如此。因此,在合作項目中,要記住這一點)。

## 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 開發(fā)的格式化標準包括括號樣式、數(shù)組聲明、多行函數(shù)調(diào)用指南、類型聲明、神奇常量和展開運算符:

// 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;

面向?qū)ο缶幊?(OOP) — 這些標準包括每個文件僅使用一種對象結(jié)構(gòu)、提供使用特征use語句的指南、確保始終聲明可見性、概述可見性和修飾符的順序以及概述對象實例化的規(guī)則:

// 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();

控制結(jié)構(gòu)– 控制結(jié)構(gòu)包括 using elseif、 notelse if和 Yoda 條件準則。Yoda 語句:在邏輯比較中將變量與常量、文字或函數(shù)調(diào)用混合時,將變量放在右側(cè)以防止意外賦值,如下所示:

// 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.

// DO
--$a;

// DON'T
$a--;
  • 數(shù)據(jù)庫——數(shù)據(jù)庫編碼標準提供了執(zhí)行數(shù)據(jù)庫查詢和格式化 SQL 語句的說明。
  • 其他建議– 其他建議包括標準,例如對函數(shù)參數(shù)使用不言自明的標志值、巧妙的代碼、閉包(匿名函數(shù))、正則表達式、shell 命令和要避免的指令extract()。

PHP 代碼的 WordPress 內(nèi)聯(lián)文檔標準

除了上述指南之外,WordPress 還提供PHP 代碼的內(nèi)聯(lián)文檔標準。 WordPress 使用自定義的文檔架構(gòu),該架構(gòu)從 PHPDoc 語法中汲取靈感,PHPDoc 語法是一種不斷發(fā)展的標準,用于為phpDocumentor維護的 PHP 代碼提供文檔。這些標準簡化了外部文檔的生成,并通過促進對代碼庫結(jié)構(gòu)的共同理解為更廣泛的 WordPress 開發(fā)人員社區(qū)做出了貢獻。

圖片[3]-WordPress 編碼標準簡介-光子波動網(wǎng) | 專業(yè)WordPress修復服務,全球范圍,快速響應

WordPress 中的 PHP 文檔大多顯示為格式化塊或內(nèi)聯(lián)注釋。在 WordPress 文件中記錄以下內(nèi)容:

  • 函數(shù)和類方法
  • Classes
  • 類成員,包括屬性和常量
  • 需要并包含
  • 掛鉤(操作和過濾器)
  • 內(nèi)嵌評論
  • 文件頭
  • 常數(shù)

WordPress 中的 HTML 和 CSS 標準

WordPress 主題和插件遵循嚴格的HTML 編碼標準,以確保一致性、可訪問性和可維護性。該指南強調(diào)語義標記,鼓勵開發(fā)人員將 HTML 元素用于其預期目的。這種做法增強了內(nèi)容結(jié)構(gòu)并提高了搜索引擎優(yōu)化 (SEO) 性能。

HTML 代碼標準為以下方面提供了指導:

  • 驗證 —應該根據(jù)W3C 驗證器驗證所有 HTML 頁面,以確保標記格式正確。
  • 自關(guān)閉元素– 自關(guān)閉元素中的正斜杠前面應有一個空格。
<!-- DO -->
<br />

<!-- DON'T –>
<br/>

屬性和標記 —所有屬性和標記都應小寫。此外,屬性值只有在機器解釋時才應小寫。如果是為人類編寫,則應使用正確的標題大寫。

<!-- DO -->
<a  title="Link Description">Descriptive text</a>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<!-- DON'T -->
<a  TITLE="link description">Click here</a>

引號– 所有屬性都必須有一個值,并且必須使用單引號或雙引號。不引用這些值可能會導致安全漏洞。

<!-- DO -->
<input type="text" name="email" disabled="disabled" />
<input type='text' name='email' disabled='disabled' />

<!-- DON'T -->
<input type=text name=email disabled>

縮進– HTML 縮進應始終反映邏輯結(jié)構(gòu)?;旌?PHP 和 HTML 時,縮進 PHP 塊以匹配周圍的 HTML 代碼。

<!-- 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 標準還可以幫助創(chuàng)建干凈、模塊化和響應式的樣式表。他們?yōu)閺暮诵拇a到主題再到插件的協(xié)作和審查設(shè)定了基線。這些準則有助于確保代碼可讀、一致且有意義。

WordPress CSS 代碼標準強調(diào)使用特定的類來定位元素,從而促進一致且有組織的結(jié)構(gòu)。具體來說,他們概述了以下標準:

結(jié)構(gòu)

/* 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 
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. */
#selector {
    property: value;
}

價值

/* 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) {
    $selector {
        property: value;
    }        
}
圖片[4]-WordPress 編碼標準簡介-光子波動網(wǎng) | 專業(yè)WordPress修復服務,全球范圍,快速響應

自2003年誕生以來,WordPress的HTML和CSS編碼標準一直與萬維網(wǎng)聯(lián)盟(W3C)的HTML和CSS指南保持一致。W3C 標準強調(diào)整合響應式設(shè)計原則和語義標記,從發(fā)布 HTML5 和 CSS3 開始,就對主題和插件的開發(fā)產(chǎn)生了影響。

采用 W3C 準則可確保 WordPress 網(wǎng)站遵守全球網(wǎng)絡標準,增強互操作性和用戶體驗,并反映出在更廣泛的網(wǎng)絡生態(tài)系統(tǒng)中保持最新、安全和兼容的承諾。

在 WordPress 中遵守這些準則強調(diào)針對W3C HTML 標記驗證器進行 HTML 質(zhì)量驗證。

這些 HTML 和 CSS 標準可確保 WordPress 網(wǎng)站在跨平臺時具有視覺吸引力、用戶友好和高效的表現(xiàn)形式。它們支持無縫的用戶體驗,并促進了 WordPress 生態(tài)系統(tǒng)不同方面的開發(fā)人員之間的協(xié)作。


聯(lián)系我們
教程看不懂?聯(lián)系我們?yōu)槟赓M解答!免費助力個人,小企站點!
客服微信
客服微信
電話:020-2206-9892
QQ咨詢:1025174874
郵件:info@361sale.com
工作時間:周一至周五,9:30-18:30,節(jié)假日休息
? 轉(zhuǎn)載聲明
本文作者:Harry
THE END
喜歡就支持一下吧
點贊0 分享
評論 搶沙發(fā)

請登錄后發(fā)表評論

    暫無評論內(nèi)容