wp-guidelines
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWordPress Coding Standards & Conventions
WordPress编码标准与规范
Quick-reference for WordPress PHP development. Rules are distilled from the official WordPress Coding Standards (WPCS) sniffs and WordPress core documentation.
WordPress PHP开发速查指南。规则提炼自官方WordPress编码标准(WPCS)检测规则及WordPress核心文档。
1. Naming Conventions
1. 命名规范
All names use for functions, variables, and properties. Classes use with underscores (). Hook names are all-lowercase with underscores, prefixed with your plugin slug.
snake_casePascal_CaseMy_Plugin_Admin| Element | Convention | Example |
|---|---|---|
| Functions | | |
| Variables | | |
| Classes | | |
| Constants | | |
| Files | | |
| Hook names | | |
| Post type slugs | | |
File naming rules: All lowercase, hyphens as separators, prefix for single-class files.
class-Global prefix rule: ALL plugin/theme globals (functions, classes, constants, hooks, namespaces) must start with a unique prefix (min 4 chars). Blocked prefixes: , , , .
wordpresswp_phpPost type slugs: Max 20 chars, no reserved names (, , , etc.), no prefix.
<!-- Detailed code examples: resources/naming-best-practices.md -->
postpageattachmentwp_函数、变量和属性全部使用命名法。类使用带下划线的命名法(如)。钩子名称使用全小写加下划线,前缀为你的插件别名。
snake_casePascal_CaseMy_Plugin_Admin| 元素 | 规范 | 示例 |
|---|---|---|
| 函数 | | |
| 变量 | | |
| 类 | 带下划线的 | |
| 常量 | | |
| 文件 | 全小写连字符分隔 | |
| 钩子名称 | 全小写加下划线 | |
| 自定义文章类型别名 | 全小写,仅含 | |
文件命名规则: 全部使用小写,用连字符分隔,单类文件需加前缀。
class-全局前缀规则: 所有插件/主题的全局内容(函数、类、常量、钩子、命名空间)必须以唯一前缀开头(至少4个字符)。禁止使用的前缀:、、、。
wordpresswp_php自定义文章类型别名: 最多20字符,不能使用保留名称(、、等),不能加前缀。
<!-- 详细代码示例:resources/naming-best-practices.md -->
postpageattachmentwp_2. PHP Best Practices (WordPress-Specific)
2. WordPress专属PHP最佳实践
Yoda conditions: Place literals on the LEFT side of , , , comparisons.
==!====!==Strict comparisons: Always pass as third arg to , , .
truein_array()array_search()array_keys()Forbidden functions:
| Function | Why | Alternative |
|---|---|---|
| Pollutes local scope unpredictably | Destructure manually |
| Hides errors | Check return values; use |
| Breaks interoperability | Use WP constants ( |
Development-only functions (remove before shipping): , , , , , , and related debug functions.
var_dumpvar_exportprint_rerror_logtrigger_errorphpinfoUse WordPress functions over PHP natives:
| PHP Native | WordPress Alternative |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
Note: for local files (using , , ) is acceptable.
file_get_contents()ABSPATHWP_CONTENT_DIRplugin_dir_path()Type casts: Use short forms: , , , . Never , , or .
<!-- Detailed code examples: resources/naming-best-practices.md -->
(int)(float)(bool)(string)(integer)(real)(unset)Yoda条件: 在、、、比较中,将字面量放在左侧。
==!====!==严格比较: 调用、、时,第三个参数必须传入。
in_array()array_search()array_keys()true禁用函数:
| 函数 | 原因 | 替代方案 |
|---|---|---|
| 不可预测地污染局部作用域 | 手动解构 |
| 隐藏错误 | 检查返回值;使用 |
| 破坏互操作性 | 使用WP常量(如 |
仅开发环境可用函数(发布前需移除):、、、、、及相关调试函数。
var_dumpvar_exportprint_rerror_logtrigger_errorphpinfo优先使用WordPress函数而非PHP原生函数:
| PHP原生函数 | WordPress替代函数 |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
注意:使用、、读取本地文件时,是可接受的。
ABSPATHWP_CONTENT_DIRplugin_dir_path()file_get_contents()类型转换: 使用短格式:、、、。禁止使用、或。
<!-- 详细代码示例:resources/naming-best-practices.md -->
(int)(float)(bool)(string)(integer)(real)(unset)3. Hooks & Actions
3. 钩子与动作
3.1 Registration Patterns
3.1 注册模式
php
// Actions: side effects (send email, save data, enqueue assets)
add_action( 'init', 'acme_register_post_types' );
add_action( 'wp_enqueue_scripts', 'acme_enqueue_assets' );
add_action( 'admin_menu', 'acme_add_admin_page' );
// Filters: modify and return a value
add_filter( 'the_content', 'acme_append_cta' );
add_filter( 'excerpt_length', 'acme_custom_excerpt_length' );php
// 动作:处理副作用(发送邮件、保存数据、入队资源)
add_action( 'init', 'acme_register_post_types' );
add_action( 'wp_enqueue_scripts', 'acme_enqueue_assets' );
add_action( 'admin_menu', 'acme_add_admin_page' );
// 过滤器:修改并返回值
add_filter( 'the_content', 'acme_append_cta' );
add_filter( 'excerpt_length', 'acme_custom_excerpt_length' );3.2 Priority and Argument Count
3.2 优先级与参数数量
php
// Default priority is 10, default accepted args is 1
add_filter( 'the_title', 'acme_modify_title', 10, 2 );
function acme_modify_title( $title, $post_id ) {
// Always declare the correct number of parameters
return $title;
}php
// 默认优先级为10,默认接受参数数量为1
add_filter( 'the_title', 'acme_modify_title', 10, 2 );
function acme_modify_title( $title, $post_id ) {
// 必须声明正确数量的参数
return $title;
}3.3 Removing Hooks
3.3 移除钩子
Must match the exact callback, priority, and (for objects) the same instance:
php
// Remove a function callback
remove_action( 'wp_head', 'wp_generator' );
// Remove with matching priority
remove_filter( 'the_content', 'acme_append_cta', 10 );
// Remove an object method (must be same instance)
remove_action( 'init', array( $instance, 'init' ) );必须匹配完全相同的回调函数、优先级,以及(针对对象)同一实例:
php
// 移除函数回调
remove_action( 'wp_head', 'wp_generator' );
// 匹配优先级移除
remove_filter( 'the_content', 'acme_append_cta', 10 );
// 移除对象方法(必须是同一实例)
remove_action( 'init', array( $instance, 'init' ) );3.4 Hook Naming Conventions
3.4 钩子命名规范
php
// Plugin hooks should be prefixed and use underscores
do_action( 'acme_before_render', $context );
$value = apply_filters( 'acme_output_format', $default, $post );
// Dynamic hooks: prefix the static part
do_action( "acme_process_{$type}", $data );php
// 插件钩子需加前缀并使用下划线
do_action( 'acme_before_render', $context );
$value = apply_filters( 'acme_output_format', $default, $post );
// 动态钩子:前缀为静态部分
do_action( "acme_process_{$type}", $data );4. Internationalization (i18n)
4. 国际化(i18n)
4.1 Core Functions
4.1 核心函数
| Function | Purpose |
|---|---|
| Return translated string |
| Echo translated string |
| Return with disambiguation context |
| Echo with disambiguation context |
| Pluralization |
| Plural + context |
| Return translated + HTML-escaped |
| Echo translated + HTML-escaped |
| Return translated + attribute-escaped |
| Echo translated + attribute-escaped |
| Return translated + escaped + context |
| Return translated + escaped + context |
| 函数 | 用途 |
|---|---|
| 返回翻译后的字符串 |
| 输出翻译后的字符串 |
| 返回带消歧上下文的翻译字符串 |
| 输出带消歧上下文的翻译字符串 |
| 复数处理 |
| 复数处理+上下文 |
| 返回翻译并经过HTML转义的字符串 |
| 输出翻译并经过HTML转义的字符串 |
| 返回翻译并经过属性转义的字符串 |
| 输出翻译并经过属性转义的字符串 |
| 返回翻译、转义并带上下文的字符串 |
| 返回翻译、转义并带上下文的字符串 |
4.2 Rules
4.2 规则
- Text domain must match your plugin/theme slug exactly.
- All user-facing strings must be wrapped in a translation function.
- Prefer combined escape+translate over separate calls:
php
// BAD - separate escape and translate
echo esc_html( __( 'Hello', 'acme-plugin' ) );
// GOOD - combined function
echo esc_html__( 'Hello', 'acme-plugin' );If you pass two parameters to or , you probably meant / .
esc_html()esc_attr()esc_html__()esc_attr__()- 文本域必须与你的插件/主题别名完全一致。
- 所有面向用户的字符串必须包裹在翻译函数中。
- 优先使用转义+翻译的组合函数,而非分开调用:
php
// 错误示例:分开转义和翻译
echo esc_html( __( 'Hello', 'acme-plugin' ) );
// 正确示例:使用组合函数
echo esc_html__( 'Hello', 'acme-plugin' );如果向或传递两个参数,你可能实际需要的是 / 。
esc_html()esc_attr()esc_html__()esc_attr__()4.3 Translator Comments
4.3 译者注释
Add translator comments for ambiguous strings, sprintf placeholders, or context:
php
// BAD
printf( __( '%s: %s', 'acme-plugin' ), $label, $value );
// GOOD
/* translators: 1: field label, 2: field value */
printf( __( '%1$s: %2$s', 'acme-plugin' ), $label, $value );对于歧义字符串、sprintf占位符或需要上下文的内容,添加译者注释:
php
// 错误示例
printf( __( '%s: %s', 'acme-plugin' ), $label, $value );
// 正确示例
/* translators: 1: 字段标签, 2: 字段值 */
printf( __( '%1$s: %2$s', 'acme-plugin' ), $label, $value );4.4 sprintf Placeholder Rules
4.4 sprintf占位符规则
- With 2+ placeholders, use ordered placeholders: ,
%1$s(not%2$s,%s).%s - Do NOT use if there is only one placeholder (use
%1$s).%s - The number of placeholders must match the number of arguments.
- 当有2个及以上占位符时,使用有序占位符:、
%1$s(而非%2$s、%s)。%s - 若只有一个占位符,禁止使用(使用
%1$s即可)。%s - 占位符数量必须与参数数量匹配。
5. Enqueuing Assets
5. 资源入队
5.1 Never Use Direct Tags
5.1 禁止直接输出标签
php
// BAD - direct output
echo '<script src="my-script.js"></script>';
echo '<link rel="stylesheet" href="my-style.css">';
// GOOD - proper enqueue
function acme_enqueue_assets() {
wp_enqueue_script(
'acme-main',
plugin_dir_url( __FILE__ ) . 'js/main.js',
array( 'jquery' ),
'1.2.0',
true // in_footer
);
wp_enqueue_style(
'acme-styles',
plugin_dir_url( __FILE__ ) . 'css/styles.css',
array(),
'1.2.0'
);
}
add_action( 'wp_enqueue_scripts', 'acme_enqueue_assets' );php
// 错误示例:直接输出
echo '<script src="my-script.js"></script>';
echo '<link rel="stylesheet" href="my-style.css">';
// 正确示例:使用标准入队方式
function acme_enqueue_assets() {
wp_enqueue_script(
'acme-main',
plugin_dir_url( __FILE__ ) . 'js/main.js',
array( 'jquery' ),
'1.2.0',
true // 在页脚加载
);
wp_enqueue_style(
'acme-styles',
plugin_dir_url( __FILE__ ) . 'css/styles.css',
array(),
'1.2.0'
);
}
add_action( 'wp_enqueue_scripts', 'acme_enqueue_assets' );5.2 Required Parameters
5.2 必填参数
| Parameter | Required? | Notes |
|---|---|---|
| Yes | Unique identifier |
| Conditional | Omit only when registering dependency-only handle |
| Recommended | Array of dependency handles |
| Yes (when src given) | Must be non-false; use explicit version string. |
| Yes | Explicitly set |
| Optional | Default |
php
// BAD - missing version, missing in_footer
wp_enqueue_script( 'acme-main', $url );
// GOOD
wp_enqueue_script( 'acme-main', $url, array(), '1.0.0', true );| 参数 | 是否必填 | 说明 |
|---|---|---|
| 是 | 唯一标识符 |
| 可选 | 仅当注册仅作为依赖的句柄时可省略 |
| 推荐 | 依赖句柄数组 |
| 是(当提供$src时) | 必须为非false值;使用明确的版本字符串。 |
| 是 | 显式设置 |
| 可选 | 默认值为 |
php
// 错误示例:缺少版本和in_footer参数
wp_enqueue_script( 'acme-main', $url );
// 正确示例
wp_enqueue_script( 'acme-main', $url, array(), '1.0.0', true );5.3 Conditional Loading
5.3 条件加载
Load assets only where needed:
php
function acme_admin_assets( $hook ) {
if ( 'toplevel_page_acme-settings' !== $hook ) {
return;
}
wp_enqueue_style( 'acme-admin', ... );
}
add_action( 'admin_enqueue_scripts', 'acme_admin_assets' );
function acme_frontend_assets() {
if ( ! is_singular( 'acme_portfolio' ) ) {
return;
}
wp_enqueue_script( 'acme-portfolio', ... );
}
add_action( 'wp_enqueue_scripts', 'acme_frontend_assets' );仅在需要的场景加载资源:
php
function acme_admin_assets( $hook ) {
if ( 'toplevel_page_acme-settings' !== $hook ) {
return;
}
wp_enqueue_style( 'acme-admin', ... );
}
add_action( 'admin_enqueue_scripts', 'acme_admin_assets' );
function acme_frontend_assets() {
if ( ! is_singular( 'acme_portfolio' ) ) {
return;
}
wp_enqueue_script( 'acme-portfolio', ... );
}
add_action( 'wp_enqueue_scripts', 'acme_frontend_assets' );6. WordPress API Usage
6. WordPress API使用规则
Key rules for WordPress API calls. Use capabilities (not roles) in . Cron intervals must be 15+ minutes. Limit (no ). Never overwrite WP globals (, ). Always pass to . Avoid -- use for UTC or for formatted local time.
current_user_can()posts_per_page-1$post$wp_query$singleget_post_meta()current_time( 'timestamp' )time()current_time( 'mysql' )Common capabilities: , , , , , , , .
manage_optionsedit_postsedit_others_postspublish_postsdelete_postsupload_filesedit_theme_optionsactivate_pluginsget_post_meta()$singleget_post_metaget_user_metaget_term_metaget_comment_metaget_site_metaget_metadataget_metadata_rawget_metadata_defaultWordPress API调用的核心规则。在中使用权限(而非角色)。Cron任务间隔必须不少于15分钟。限制(禁止使用)。禁止覆盖WP全局变量(如、)。调用时必须传入参数。避免使用——使用获取UTC时间,或获取格式化的本地时间。
current_user_can()posts_per_page-1$post$wp_queryget_post_meta()$singlecurrent_time( 'timestamp' )time()current_time( 'mysql' )常用权限:、、、、、、、。
manage_optionsedit_postsedit_others_postspublish_postsdelete_postsupload_filesedit_theme_optionsactivate_plugins$singleget_post_metaget_user_metaget_term_metaget_comment_metaget_site_metaget_metadataget_metadata_rawget_metadata_default7. Deprecated Functions (Common Replacements)
7. 废弃函数(常见替代方案)
Common deprecated functions and their replacements. WPCS flags usage as an error if the function was deprecated before your configured minimum WP version, and a warning otherwise.
| Deprecated | Since | Replacement |
|---|---|---|
| 4.5 | |
| 6.2 | |
| 3.0 | |
| 3.0 | |
| 2.1 | |
| 3.0 | |
| 3.0 | |
| 3.0 | |
| 4.6 | |
| 4.0 | |
| 4.0 | |
| 4.4 | |
| 4.4 | |
| 5.7 | |
| 5.5 | |
| 5.5 | |
| 5.5 | |
| 6.3 | |
| 6.0.2 | |
| 5.9 | |
| 2.8 | |
| 2.8 | |
| 2.8 | |
| 3.0 | |
| 6.9 | |
| 6.7 | |
常见的废弃函数及其替代方案。如果函数在你配置的最低WP版本之前已被废弃,WPCS会将其标记为错误;否则标记为警告。
| 废弃函数 | 废弃版本 | 替代方案 |
|---|---|---|
| 4.5 | |
| 6.2 | |
| 3.0 | |
| 3.0 | |
| 2.1 | |
| 3.0 | |
| 3.0 | |
| 3.0 | |
| 4.6 | |
| 4.0 | |
| 4.0 | |
| 4.4 | |
| 4.4 | |
| 5.7 | |
| 5.5 | |
| 5.5 | |
| 5.5 | |
| 6.3 | |
| 6.0.2 | |
| 5.9 | |
| 2.8 | |
| 2.8 | |
| 2.8 | |
| 3.0 | |
| 6.9 | |
| 6.7 | |
8. Formatting
8. 格式规范
Spacing: WordPress uses spaces inside parentheses, brackets, and around operators. Control structures always have spaces after keywords and inside parens: , .
if ( $x )foreach ( $arr as $v )Indentation: Use tabs, not spaces. Multi-line arrays: one item per line, trailing comma.
Operator spacing: Spaces around , , , , etc. No spaces around or .
=+.=>->?->Cast spacing: Space after cast, no space inside: .
<!-- Detailed code examples: resources/api-deprecated-formatting.md -->
(int) $val空格: WordPress要求在括号、方括号内以及运算符两侧添加空格。控制结构的关键字后必须加空格,且括号内也要加空格:、。
if ( $x )foreach ( $arr as $v )缩进: 使用制表符,而非空格。多行数组:每行一个元素,末尾加逗号。
运算符空格: 在、、、等运算符两侧加空格。或两侧不加空格。
=+.=>->?->类型转换空格: 类型转换后加空格,括号内不加空格:。
<!-- 详细代码示例:resources/api-deprecated-formatting.md -->
(int) $val9. Testing
9. 测试
PHP: Use PHPUnit with . Install via or . Test files in , named .
WP_UnitTestCasecomposer require --dev phpunit/phpunitwp scaffold plugin-teststests/test-class-{name}.phpJavaScript: Use (bundles Jest): . E2E via .
@wordpress/scriptsnpx wp-scripts test-unit-js@wordpress/e2e-test-utilsLinting: for PHP. and for JS/CSS.
<!-- Detailed code examples: resources/testing-patterns.md -->
vendor/bin/phpcs --standard=WordPress src/npx wp-scripts lint-jsnpx wp-scripts lint-stylePHP: 使用PHPUnit搭配。可通过或安装。测试文件放在目录下,命名格式为。
WP_UnitTestCasecomposer require --dev phpunit/phpunitwp scaffold plugin-teststests/test-class-{name}.phpJavaScript: 使用(内置Jest):。端到端测试使用。
@wordpress/scriptsnpx wp-scripts test-unit-js@wordpress/e2e-test-utils代码检查: PHP使用。JS/CSS使用和。
<!-- 详细代码示例:resources/testing-patterns.md -->
vendor/bin/phpcs --standard=WordPress src/npx wp-scripts lint-jsnpx wp-scripts lint-style10. Quick Reference Tables
10. 速查表
Control Structure Spacing
控制结构空格
| Pattern | BAD | GOOD |
|---|---|---|
| if | | |
| elseif | | |
| foreach | | |
| for | | |
| switch | | |
| while | | |
| 模式 | 错误示例 | 正确示例 |
|---|---|---|
| if | | |
| elseif | | |
| foreach | | |
| for | | |
| switch | | |
| while | | |
Naming Quick Reference
命名速查
| Element | Convention | Example |
|---|---|---|
| Functions | | |
| Variables | | |
| Classes | | |
| Constants | | |
| Files | | |
| Hook names | | |
| Post type slugs | | |
| 元素 | 规范 | 示例 |
|---|---|---|
| 函数 | | |
| 变量 | | |
| 类 | 带下划线的 | |
| 常量 | | |
| 文件 | 全小写连字符分隔 | |
| 钩子名称 | 全小写加下划线 | |
| 自定义文章类型别名 | 全小写,仅含 | |
WordPress i18n Functions at a Glance
WordPress国际化函数速查
| Need | Function |
|---|---|
| Return translated string | |
| Echo translated string | |
| Return + HTML escape | |
| Echo + HTML escape | |
| Return + attr escape | |
| Echo + attr escape | |
| With context | |
| Singular/plural | |
| Singular/plural + context | |
| 需求 | 函数 |
|---|---|
| 返回翻译后的字符串 | |
| 输出翻译后的字符串 | |
| 返回翻译并经过HTML转义的字符串 | |
| 输出翻译并经过HTML转义的字符串 | |
| 返回翻译并经过属性转义的字符串 | |
| 输出翻译并经过属性转义的字符串 | |
| 带上下文的翻译 | |
| 单复数处理 | |
| 单复数处理+上下文 | |