WordPress 开发中的编码标准对于一个强大和可持续的代码库至关重要。它们是开发人员在编写代码时遵守的准则和惯例,有助于加强协作、简化维护并确保整体可靠性。
此外,编码标准还能防止常见的陷阱和错误,提高代码质量。在 WordPress 开发中,多个贡献者通常会在一个项目上进行合作,因此编码标准是有效团队协作的基础。它们促进了沟通,缓解了潜在冲突,并有助于提高开发流程的效率。
![图片[1]-WordPress 编码标准简介-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050707431560.png)
遵守编码标准可促进各项目之间的一致性,使开发人员更容易在不同的代码库之间无缝切换。这种一致性可扩展到代码的可读性和可维护性,并促进团队成员之间的共同理解。
官方 WordPress 编码标准涵盖了凝聚力和高效开发过程的五个关键领域:
- PHP确保服务器端代码一致性
- 用于促进结构化和语义标记的HTML
- JavaScript实现有效的客户端功能
- 用于保持一致的样式方法的CSS
- 确保最终产品对具有不同需求的个人具有包容性和用户友好性的可访问性
WordPress 开发中的 PHP 标准
![图片[2]-WordPress 编码标准简介-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050707492237.jpg)
WordPress 专用PHP 编码标准可确保 WordPress 代码的一致性和可读性。WordPress 核心必须使用这些标准,主题和插件则强烈推荐使用这些标准。这些标准涵盖各个方面,包括命名规则、缩进和代码结构,以提高可读性和便于协作。
WordPress PHP 标准涵盖以下类别:
- 一般性— 这些标准包括:在 HTML 代码块中嵌入多行 PHP 代码段时,将开头和结尾的 PHP 标记单独放在一行中;使用单引号和双引号时避免使用速记 PHP 标记;以及编写 include 和 require 语句的指导原则:
// Opening and closing PHP tags within HTML:// Put open/close tags on their own lines.## DOfunction foo() {?><div><?phpecho esc_html (bar ($param1,$param2));?></div><?php}## DON'Tif ( $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 }// 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 ); ?>// 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.## DOrequire_once ABSPATH . 'file-name.php'## DON'Trequire_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' );
命名—命名标准包括命名约定和命名动态钩子的插值:
## 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 ) {}## 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 也是如此。因此,在合作项目中,要记住这一点)。
## 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]## 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 开发的格式化标准包括括号样式、数组声明、多行函数调用指南、类型声明、神奇常量和展开运算符:
// 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 appropriateindentation before a spread operator.There should be:* No space between the spread operator and thevariable/function it applies to.* No space between the spread and the referenceoperators when combined.*///DOfunction some_func( &...$arg1 ) {bar( ...$arg2 );bar(array( ...$arg3 ),...array_values( $array_vals ));}//DONTfunction 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 ) ); }// 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.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();// 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();
控制结构– 控制结构包括 using elseif
、 notelse if
和 Yoda 条件准则。Yoda 语句:在逻辑比较中将变量与常量、文字或函数调用混合时,将变量放在右侧以防止意外赋值,如下所示:
// 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// 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--;// 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()
。
PHP 代码的 WordPress 内联文档标准
除了上述指南之外,WordPress 还提供PHP 代码的内联文档标准。 WordPress 使用自定义的文档架构,该架构从 PHPDoc 语法中汲取灵感,PHPDoc 语法是一种不断发展的标准,用于为phpDocumentor维护的 PHP 代码提供文档。这些标准简化了外部文档的生成,并通过促进对代码库结构的共同理解为更广泛的 WordPress 开发人员社区做出了贡献。
![图片[3]-WordPress 编码标准简介-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050707513324.jpg)
WordPress 中的 PHP 文档大多显示为格式化块或内联注释。在 WordPress 文件中记录以下内容:
- 函数和类方法
- Classes
- 类成员,包括属性和常量
- 需要并包含
- 挂钩(操作和过滤器)
- 内嵌评论
- 文件头
- 常数
WordPress 中的 HTML 和 CSS 标准
WordPress 主题和插件遵循严格的HTML 编码标准,以确保一致性、可访问性和可维护性。该指南强调语义标记,鼓励开发人员将 HTML 元素用于其预期目的。这种做法增强了内容结构并提高了搜索引擎优化 (SEO) 性能。
HTML 代码标准为以下方面提供了指导:
- 验证 —应该根据W3C 验证器验证所有 HTML 页面,以确保标记格式正确。
- 自关闭元素– 自关闭元素中的正斜杠前面应有一个空格。
<!-- DO --><br /><!-- DON'T –><br/><!-- DO --> <br /> <!-- DON'T –> <br/><!-- DO --> <br /> <!-- DON'T –> <br/>
属性和标记 —所有属性和标记都应小写。此外,属性值只有在机器解释时才应小写。如果是为人类编写,则应使用正确的标题大写。
<!-- 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><!-- 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 --><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><!-- 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 代码。
<!-- 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; ?><!-- 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 代码标准强调使用特定的类来定位元素,从而促进一致且有组织的结构。具体来说,他们概述了以下标准:
结构:
/* DOEach selector should be on its own line ending witha comma or curly brace. The closing brace should occupythe 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; }/* 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; }
选择器:
/* DOUse 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; }/* 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 namessnd 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; }/* 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 fora 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); }/* 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;}}/* 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; } }
![图片[4]-WordPress 编码标准简介-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050707524050.jpg)
自2003年诞生以来,WordPress的HTML和CSS编码标准一直与万维网联盟(W3C)的HTML和CSS指南保持一致。W3C 标准强调整合响应式设计原则和语义标记,从发布 HTML5 和 CSS3 开始,就对主题和插件的开发产生了影响。
采用 W3C 准则可确保 WordPress 网站遵守全球网络标准,增强互操作性和用户体验,并反映出在更广泛的网络生态系统中保持最新、安全和兼容的承诺。
在 WordPress 中遵守这些准则强调针对W3C HTML 标记验证器进行 HTML 质量验证。
这些 HTML 和 CSS 标准可确保 WordPress 网站在跨平台时具有视觉吸引力、用户友好和高效的表现形式。它们支持无缝的用户体验,并促进了 WordPress 生态系统不同方面的开发人员之间的协作。
联系我们 |
---|
文章看不懂?联系我们为您免费解答!免费助力个人,小企站点! |
① 电话:020-2206-9892 |
② QQ咨询:1025174874 |
③ 邮件:info@361sale.com |
④ 工作时间:周一至周五,9:30-18:30,节假日休息 |
暂无评论内容