wp-apis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

WordPress Core APIs

WordPress核心API



1. Administration Menus

1. 后台管理菜单

php
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $callback, $icon_url, $position )
add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $callback )
Helper FunctionParent Page
add_dashboard_page()
Dashboard
add_posts_page()
Posts
add_media_page()
Media
add_pages_page()
Pages
add_comments_page()
Comments
add_theme_page()
Appearance
add_plugins_page()
Plugins
add_users_page()
Users
add_management_page()
Tools
add_options_page()
Settings
  • Hook:
    admin_menu
  • Use
    load-{$hook_suffix}
    to process form submissions before output.
  • remove_menu_page( $slug )
    /
    remove_submenu_page( $parent, $slug )
    to hide entries.

php
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $callback, $icon_url, $position )
add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $callback )
辅助函数父级页面
add_dashboard_page()
仪表盘
add_posts_page()
文章
add_media_page()
媒体
add_pages_page()
页面
add_comments_page()
评论
add_theme_page()
外观
add_plugins_page()
插件
add_users_page()
用户
add_management_page()
工具
add_options_page()
设置
  • 钩子:
    admin_menu
  • 使用
    load-{$hook_suffix}
    在输出前处理表单提交。
  • 使用
    remove_menu_page( $slug )
    /
    remove_submenu_page( $parent, $slug )
    隐藏菜单项。

2. Shortcodes

2. 短代码

php
add_shortcode( $tag, $callback )
// Callback signature: ( $atts, $content = null, $tag = '' ): string
shortcode_atts( $defaults, $atts, $tag )
do_shortcode( $content )  // Process nested shortcodes in enclosing content.
Rules:
  • Return, don't echo -- shortcodes must return HTML;
    echo
    corrupts layout.
  • Prefix names -- use a unique prefix to avoid collisions.
  • Escape output -- all attribute values through
    esc_attr()
    /
    esc_html()
    .
  • Pass
    $tag
    to
    shortcode_atts()
    to enable the
    shortcode_atts_{$tag}
    filter.

php
add_shortcode( $tag, $callback )
// Callback signature: ( $atts, $content = null, $tag = '' ): string
shortcode_atts( $defaults, $atts, $tag )
do_shortcode( $content )  // Process nested shortcodes in enclosing content.
规则:
  • 返回内容,不要直接输出 -- 短代码必须返回HTML;使用
    echo
    会破坏布局。
  • 添加前缀 -- 使用唯一前缀避免命名冲突。
  • 转义输出 -- 所有属性值通过
    esc_attr()
    /
    esc_html()
    处理。
  • $tag
    传入
    shortcode_atts()
    以启用
    shortcode_atts_{$tag}
    过滤器。

3. Custom Meta Boxes

3. 自定义元框

php
add_meta_box( $id, $title, $callback, $screen, $context, $priority )
// Contexts: normal | side | advanced
// Priorities: high | core | default | low
remove_meta_box( $id, $screen, $context )
Save handler checklist (hook:
save_post
):
  1. Verify nonce with
    wp_verify_nonce()
  2. Check
    DOING_AUTOSAVE
  3. Check
    current_user_can( 'edit_post', $post_id )
  4. Sanitize input before
    update_post_meta()

php
add_meta_box( $id, $title, $callback, $screen, $context, $priority )
// Contexts: normal | side | advanced
// Priorities: high | core | default | low
remove_meta_box( $id, $screen, $context )
保存处理检查清单(钩子:
save_post
):
  1. 使用
    wp_verify_nonce()
    验证随机数
  2. 检查
    DOING_AUTOSAVE
    状态
  3. 检查
    current_user_can( 'edit_post', $post_id )
    权限
  4. 在调用
    update_post_meta()
    前对输入内容进行清理

4. Custom Post Types & Taxonomies

4. 自定义文章类型与分类法

php
register_post_type( $post_type, $args )
register_taxonomy( $taxonomy, $object_type, $args )
Key CPT args:
public
,
has_archive
,
show_in_rest
(required for Block Editor),
supports
,
rewrite
,
menu_icon
,
capability_type
.
supports
Value
Feature Enabled
title
Title field
editor
Content editor
thumbnail
Featured image
excerpt
Excerpt field
revisions
Revision history
page-attributes
Template + menu order
custom-fields
Custom fields meta box
comments
Comments
Key taxonomy args:
hierarchical
(true = categories, false = tags),
show_in_rest
,
rewrite
,
show_admin_column
.
Template FileWhen
single-{$post_type}.php
Single CPT post
archive-{$post_type}.php
CPT archive
taxonomy-{$taxonomy}.php
Custom taxonomy archive
taxonomy-{$taxonomy}-{slug}.php
Specific term archive
  • Hook on
    init
    . Flush rewrite rules on activation only -- never on every request.

php
register_post_type( $post_type, $args )
register_taxonomy( $taxonomy, $object_type, $args )
关键CPT参数:
public
,
has_archive
,
show_in_rest
(区块编辑器必填),
supports
,
rewrite
,
menu_icon
,
capability_type
.
supports
启用的功能
title
标题字段
editor
内容编辑器
thumbnail
特色图片
excerpt
摘要字段
revisions
修订历史
page-attributes
模板 + 菜单顺序
custom-fields
自定义字段元框
comments
评论
关键分类法参数:
hierarchical
(true = 分类,false = 标签),
show_in_rest
,
rewrite
,
show_admin_column
.
模板文件适用场景
single-{$post_type}.php
单个CPT文章
archive-{$post_type}.php
CPT归档页面
taxonomy-{$taxonomy}.php
自定义分类归档页面
taxonomy-{$taxonomy}-{slug}.php
特定术语归档页面
  • init
    钩子上注册。仅在激活时刷新重写规则 -- 不要在每次请求时都执行。

5. HTTP API

5. HTTP API

php
wp_remote_get( $url, $args )
wp_remote_post( $url, $args )
wp_remote_retrieve_response_code( $response )
wp_remote_retrieve_body( $response )
is_wp_error( $response )
ArgumentDefaultNotes
method
GET
Or
POST
,
PUT
,
DELETE
, etc.
timeout
5
Seconds. Increase for slow APIs.
redirection
5
Max redirects to follow.
httpversion
1.0
Use
1.1
for keep-alive.
sslverify
true
Never disable in production.
blocking
true
false
= fire-and-forget.
  • Cache external responses with
    set_transient()
    /
    get_transient()
    .

php
wp_remote_get( $url, $args )
wp_remote_post( $url, $args )
wp_remote_retrieve_response_code( $response )
wp_remote_retrieve_body( $response )
is_wp_error( $response )
参数默认值说明
method
GET
可选值:
POST
,
PUT
,
DELETE
timeout
5
秒数。针对响应缓慢的API可适当增加。
redirection
5
最大重定向次数。
httpversion
1.0
启用长连接请使用
1.1
sslverify
true
生产环境绝对不要禁用。
blocking
true
false
= 即发即弃模式。
  • 使用
    set_transient()
    /
    get_transient()
    缓存外部响应。

6. WP-Cron

6. WP-Cron

php
wp_schedule_event( $timestamp, $recurrence, $hook, $args )
wp_schedule_single_event( $timestamp, $hook, $args )
wp_next_scheduled( $hook, $args )
wp_unschedule_event( $timestamp, $hook, $args )
Custom intervals: filter
cron_schedules
to add entries like
array( 'interval' => 300, 'display' => 'Every 5 Minutes' )
.
Rules:
  • Always guard with
    wp_next_scheduled()
    before scheduling.
  • Clean up with
    wp_unschedule_event()
    in
    register_deactivation_hook
    .
  • For production:
    define( 'DISABLE_WP_CRON', true )
    + system crontab running
    wp cron event run --due-now
    .

php
wp_schedule_event( $timestamp, $recurrence, $hook, $args )
wp_schedule_single_event( $timestamp, $hook, $args )
wp_next_scheduled( $hook, $args )
wp_unschedule_event( $timestamp, $hook, $args )
自定义时间间隔: 通过
cron_schedules
过滤器添加条目,例如
array( 'interval' => 300, 'display' => 'Every 5 Minutes' )
规则:
  • 调度前务必使用
    wp_next_scheduled()
    进行检查。
  • register_deactivation_hook
    中使用
    wp_unschedule_event()
    清理任务。
  • 生产环境建议: 定义
    define( 'DISABLE_WP_CRON', true )
    + 系统定时任务执行
    wp cron event run --due-now

7. Dashboard Widgets

7. 仪表盘小工具

php
wp_add_dashboard_widget( $widget_id, $widget_name, $callback )
// Hook: wp_dashboard_setup
  • For side column: use
    add_meta_box()
    with
    'dashboard'
    screen and
    'side'
    context.
  • Remove defaults:
    remove_meta_box( $id, 'dashboard', $context )
    .

php
wp_add_dashboard_widget( $widget_id, $widget_name, $callback )
// 钩子: wp_dashboard_setup
  • 如需添加到侧边栏:使用
    add_meta_box()
    ,指定
    'dashboard'
    屏幕和
    'side'
    上下文。
  • 移除默认小工具:
    remove_meta_box( $id, 'dashboard', $context )

8. Users & Roles

8. 用户与角色

php
add_role( $role, $display_name, $capabilities )
remove_role( $role )
$role->add_cap( $cap )  // via get_role()
$role->remove_cap( $cap )
current_user_can( $capability )
User Meta:
php
update_user_meta( $user_id, $key, $value )
get_user_meta( $user_id, $key, $single )
delete_user_meta( $user_id, $key )
WP_User_Query: accepts
role
,
orderby
,
order
,
number
,
meta_query
.
  • Roles persist in DB -- add on activation, remove on uninstall.

php
add_role( $role, $display_name, $capabilities )
remove_role( $role )
$role->add_cap( $cap )  // via get_role()
$role->remove_cap( $cap )
current_user_can( $capability )
用户元数据:
php
update_user_meta( $user_id, $key, $value )
get_user_meta( $user_id, $key, $single )
delete_user_meta( $user_id, $key )
WP_User_Query: 支持
role
,
orderby
,
order
,
number
,
meta_query
参数。
  • 角色会持久化存储在数据库中 -- 在激活时添加,卸载时移除。

9. Privacy API

9. 隐私API

WordPress 4.9.6+ GDPR/privacy tools. Plugins storing personal data should register exporters and erasers.
Filters:
  • wp_privacy_personal_data_exporters
    -- register exporter callback returning
    array( 'data' => [...], 'done' => bool )
    .
  • wp_privacy_personal_data_erasers
    -- register eraser callback returning
    array( 'items_removed' => int, 'items_retained' => int, 'messages' => [], 'done' => bool )
    .
Privacy policy:
wp_add_privacy_policy_content( $plugin_name, $policy_text )
on
admin_init
.
  • Use
    $page
    parameter and
    'done' => false
    for large datasets.

WordPress 4.9.6+ 新增GDPR/隐私工具。存储个人数据的插件应注册导出器和擦除器。
过滤器:
  • wp_privacy_personal_data_exporters
    -- 注册导出器回调,返回
    array( 'data' => [...], 'done' => bool )
    格式的数据。
  • wp_privacy_personal_data_erasers
    -- 注册擦除器回调,返回
    array( 'items_removed' => int, 'items_retained' => int, 'messages' => [], 'done' => bool )
    格式的数据。
隐私政策:
admin_init
钩子上使用
wp_add_privacy_policy_content( $plugin_name, $policy_text )
添加内容。
  • 针对大型数据集,使用
    $page
    参数并设置
    'done' => false
    进行分页处理。

10. Theme Modification API

10. 主题修改API

php
set_theme_mod( $name, $value )
get_theme_mod( $name, $default )
remove_theme_mod( $name )
get_theme_mods()
Feature
theme_mod
option
ScopePer-themeGlobal (all themes)
Switching themesReverts to new theme's valuesPersists
StorageSingle
theme_mods_{$theme}
row
Individual option rows
Customizer defaultYes (
type => 'theme_mod'
)
Must set
type => 'option'
Filter
theme_mod_{$name}
option_{$name}
Use
theme_mod
for visual/display settings. Use
option
for functional plugin settings.

php
set_theme_mod( $name, $value )
get_theme_mod( $name, $default )
remove_theme_mod( $name )
get_theme_mods()
特性
theme_mod
option
作用范围按主题划分全局(所有主题共享)
切换主题时恢复为新主题的默认值保持不变
存储方式单个
theme_mods_{$theme}
独立的选项行
自定义器默认支持是(
type => 'theme_mod'
必须设置
type => 'option'
过滤器
theme_mod_{$name}
option_{$name}
视觉/显示设置使用
theme_mod
,功能性插件设置使用
option

11. Site Health API

11. 站点健康API

Custom tab: filter
site_health_navigation_tabs
, action
site_health_tab_content
.
Custom status test: filter
site_status_tests
with
$tests['direct']['key'] = array( 'label' => ..., 'test' => $callback )
.
Test callback returns:
label
,
status
(good | recommended | critical),
badge
(label + color),
description
,
actions
,
test
.
Debug info: filter
debug_information
to add fields under
$info['plugin-slug']['fields']
.

自定义标签页: 使用
site_health_navigation_tabs
过滤器和
site_health_tab_content
动作。
自定义状态测试: 使用
site_status_tests
过滤器,格式为
$tests['direct']['key'] = array( 'label' => ..., 'test' => $callback )
测试回调返回内容包含:
label
,
status
(good | recommended | critical),
badge
(标签+颜色),
description
,
actions
,
test
调试信息: 使用
debug_information
过滤器在
$info['plugin-slug']['fields']
下添加字段。

12. Global Variables

12. 全局变量

Inside the Loop

循环内部

VariableTypeDescription
$post
WP_Post
Current post being processed
$authordata
WP_User
Current post's author
$page
int
Current page of a paginated post
$multipage
bool
Whether post has
<!--nextpage-->
splits
$numpages
int
Total pages in paginated post
$more
bool
Whether to show content past
<!--more-->
变量类型描述
$post
WP_Post
当前正在处理的文章
$authordata
WP_User
当前文章的作者
$page
int
分页文章的当前页码
$multipage
bool
文章是否包含
<!--nextpage-->
分页标记
$numpages
int
分页文章的总页数
$more
bool
是否显示
<!--more-->
之后的内容

Core Objects

核心对象

VariableTypePreferred API
$wpdb
wpdb
No alternative -- use directly
$wp_query
WP_Query
Template tags:
have_posts()
,
the_post()
$wp_rewrite
WP_Rewrite
get_option('permalink_structure')
$wp_roles
WP_Roles
wp_roles()
,
current_user_can()
$wp_admin_bar
WP_Admin_Bar
add_action('admin_bar_menu', ...)
$wp_locale
WP_Locale
wp_date()
,
date_i18n()
变量类型推荐使用的API
$wpdb
wpdb
无替代方案 -- 直接使用
$wp_query
WP_Query
模板标签:
have_posts()
,
the_post()
$wp_rewrite
WP_Rewrite
get_option('permalink_structure')
$wp_roles
WP_Roles
wp_roles()
,
current_user_can()
$wp_admin_bar
WP_Admin_Bar
add_action('admin_bar_menu', ...)
$wp_locale
WP_Locale
wp_date()
,
date_i18n()

Admin & Version

后台与版本

VariableTypeDescription
$pagenow
string
Current admin page filename
$post_type
string
Current post type in admin screens
$wp_version
string
WordPress version number
$wp_db_version
int
Database schema version
变量类型描述
$pagenow
string
当前后台页面的文件名
$post_type
string
后台屏幕中当前的文章类型
$wp_version
string
WordPress版本号
$wp_db_version
int
数据库架构版本

Server Detection

服务器检测

VariableTypeTrue when...
$is_apache
bool
Running on Apache
$is_nginx
bool
Running on Nginx
$is_IIS
bool
Running on IIS
变量类型为true的场景
$is_apache
bool
运行在Apache服务器上
$is_nginx
bool
运行在Nginx服务器上
$is_IIS
bool
运行在IIS服务器上

Best Practices

最佳实践

  • Use API functions first --
    get_queried_object()
    instead of
    global $wp_query; $wp_query->get_queried_object()
    .
  • Always declare
    global
    before use:
    global $wpdb;
  • Never modify
    $post
    without
    wp_reset_postdata()
    afterward.
  • $wpdb
    is the exception
    -- it has no wrapper and must be used directly for custom queries.

  • 优先使用API函数 -- 例如使用
    get_queried_object()
    代替
    global $wp_query; $wp_query->get_queried_object()
  • 使用前必须声明
    global
    -- 例如
    global $wpdb;
  • 修改
    $post
    后必须调用
    wp_reset_postdata()
    -- 避免影响后续代码。
  • $wp_db
    是例外
    -- 它没有封装函数,自定义查询必须直接使用。

13. Responsive Images

13. 响应式图片

php
wp_get_attachment_image( $attachment_id, $size )           // Full <img> with srcset/sizes.
wp_get_attachment_image_srcset( $attachment_id, $size )    // Just srcset string.
wp_get_attachment_image_sizes( $attachment_id, $size )     // Just sizes string.
add_image_size( $name, $width, $height, $crop )            // Register custom size.
Filters:
  • wp_calculate_image_sizes
    -- override
    sizes
    attribute for your layout.
  • wp_calculate_image_srcset
    -- modify source list (e.g., remove oversized sources).
  • max_srcset_image_width
    -- cap max width in srcset (default 2048px).
WordPress 5.5+ adds
loading="lazy"
automatically. Pass
'loading' => 'eager'
for above-the-fold images.

php
wp_get_attachment_image( $attachment_id, $size )           // 生成包含srcset/sizes的完整<img>标签。
wp_get_attachment_image_srcset( $attachment_id, $size )    // 仅返回srcset字符串。
wp_get_attachment_image_sizes( $attachment_id, $size )     // 仅返回sizes字符串。
add_image_size( $name, $width, $height, $crop )            // 注册自定义图片尺寸。
过滤器:
  • wp_calculate_image_sizes
    -- 覆盖布局中的
    sizes
    属性。
  • wp_calculate_image_srcset
    -- 修改图片源列表(例如移除过大的图片源)。
  • max_srcset_image_width
    -- 限制srcset中的最大宽度(默认2048px)。
WordPress 5.5+会自动添加
loading="lazy"
属性。对于首屏图片,可传入
'loading' => 'eager'

14. Advanced Hooks

14. 高级钩子

php
remove_action( $hook, $callback, $priority )
remove_filter( $hook, $callback, $priority )
do_action( $hook, ...$args )       // Fire a custom action.
apply_filters( $hook, $value, ...$args )  // Fire a custom filter.
FunctionReturns
did_action()
Number of times an action has fired (int).
doing_action()
Whether a specific action is currently running.
doing_filter()
Whether a specific filter is currently running.
current_action()
Name of the action currently being executed.
current_filter()
Name of the current filter (works for actions).
has_action()
Whether a callback is registered for an action.
has_filter()
Whether a callback is registered for a filter.
Rules:
  • Removal must happen after the original
    add_action()
    and at the same priority.
  • Use
    did_action() > 1
    guard to prevent recursive triggers in
    save_post
    .
  • Prefix all custom hook names. Document with
    @since
    /
    @param
    . Never change signatures after release.

php
remove_action( $hook, $callback, $priority )
remove_filter( $hook, $callback, $priority )
do_action( $hook, ...$args )       // 触发自定义动作。
apply_filters( $hook, $value, ...$args )  // 触发自定义过滤器。
函数返回值
did_action()
动作触发的次数(整数)。
doing_action()
是否正在执行特定动作。
doing_filter()
是否正在执行特定过滤器。
current_action()
当前正在执行的动作名称。
current_filter()
当前的过滤器名称(也适用于动作)。
has_action()
是否为某个动作注册了回调函数。
has_filter()
是否为某个过滤器注册了回调函数。
规则:
  • 移除动作必须在原
    add_action()
    之后执行,且优先级必须一致。
  • save_post
    中使用
    did_action() > 1
    防止递归触发。
  • 所有自定义钩子名称添加前缀。使用
    @since
    /
    @param
    注释文档。发布后不要修改参数签名。

15. Common Mistakes

15. 常见错误

MistakeFix
Flushing rewrite rules on every requestOnly flush on activation:
register_activation_hook
+
flush_rewrite_rules()
Registering CPTs/taxonomies in
admin_init
Use
init
-- they must be available on the frontend too
echo
inside a shortcode handler
Always
return
the HTML string
Saving meta without nonce/capability checkVerify nonce, check
DOING_AUTOSAVE
, check
current_user_can()
Scheduling cron without
wp_next_scheduled()
guard
Always check first or you create duplicate events
Not cleaning up cron on deactivation
wp_unschedule_event()
in
register_deactivation_hook
Using
$wpdb->query()
for HTTP API work
Use
wp_remote_get()
/
wp_remote_post()
Disabling
sslverify
in production
Only disable for local development; never in production
Adding roles/caps on every page loadRoles persist in DB -- add on activation, remove on uninstall
Forgetting
show_in_rest => true
on CPTs
Required for Block Editor and REST API access
Not paginating privacy exporters/erasersSet
done => false
and use
$page
parameter
Calling
remove_action()
too early
Must run after the original
add_action()
and match priority
Using
get_option()
for theme-specific settings
Use
get_theme_mod()
-- values travel with the theme
Modifying
$post
global without reset
Always call
wp_reset_postdata()
after custom loops
Hardcoding image sizes in
srcset
Use
wp_calculate_image_srcset
filter instead
CPT slug matches a page slugIndividual CPT posts 404 -- use a different rewrite slug or rename the page
add_action('save_post', $fn)
but handler expects 3 args
Default is 1 arg -- pass
10, 3
to receive
($post_id, $post, $update)
Filters that
echo
instead of
return
Filter callbacks MUST return the modified value; echoing corrupts output

错误修复方案
每次请求都刷新重写规则仅在激活时刷新:
register_activation_hook
+
flush_rewrite_rules()
admin_init
中注册CPT/分类法
使用
init
钩子 -- 它们需要在前端也能访问
短代码处理函数中使用
echo
始终返回HTML字符串
保存元数据时未验证随机数/权限验证随机数,检查
DOING_AUTOSAVE
,检查
current_user_can()
调度Cron任务时未使用
wp_next_scheduled()
检查
必须先检查,否则会创建重复任务
停用插件时未清理Cron任务
register_deactivation_hook
中使用
wp_unschedule_event()
使用
$wpdb->query()
处理HTTP请求
使用
wp_remote_get()
/
wp_remote_post()
生产环境禁用
sslverify
仅在本地开发时禁用;生产环境绝对不要禁用
每次页面加载都添加角色/权限角色持久化存储在数据库中 -- 激活时添加,卸载时移除
自定义文章类型未设置
show_in_rest => true
区块编辑器和REST API访问必填
隐私导出器/擦除器未分页设置
done => false
并使用
$page
参数
过早调用
remove_action()
必须在原
add_action()
之后执行,且优先级匹配
使用
get_option()
存储主题特定设置
使用
get_theme_mod()
-- 配置会随主题切换
修改
$post
全局变量后未重置
自定义循环后必须调用
wp_reset_postdata()
srcset
中硬编码图片尺寸
使用
wp_calculate_image_srcset
过滤器代替
自定义文章类型slug与页面slug冲突单个CPT文章会返回404 -- 使用不同的重写slug或重命名页面
add_action('save_post', $fn)
但处理函数期望3个参数
默认仅传递1个参数 -- 需要传入
10, 3
以接收
($post_id, $post, $update)
过滤器函数使用
echo
而非
return
过滤器回调必须返回修改后的值;使用echo会破坏输出

Resources

资源

  • resources/menus-shortcodes-metaboxes.md -- Full code examples for admin menus, shortcodes, and meta boxes
  • resources/cpt-http-cron.md -- Full code examples for custom post types, HTTP API, and WP-Cron
  • resources/widgets-users-privacy.md -- Full code examples for dashboard widgets, users/roles, and privacy API
  • resources/theme-health-images-hooks.md -- Full code examples for theme mods, Site Health, responsive images, and advanced hooks
  • resources/menus-shortcodes-metaboxes.md -- 后台菜单、短代码和元框的完整代码示例
  • resources/cpt-http-cron.md -- 自定义文章类型、HTTP API和WP-Cron的完整代码示例
  • resources/widgets-users-privacy.md -- 仪表盘小工具、用户/角色和隐私API的完整代码示例
  • resources/theme-health-images-hooks.md -- 主题修改、站点健康、响应式图片和高级钩子的完整代码示例