wp-apis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWordPress 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 Function | Parent Page |
|---|---|
| Dashboard |
| Posts |
| Media |
| Pages |
| Comments |
| Appearance |
| Plugins |
| Users |
| Tools |
| Settings |
- Hook:
admin_menu - Use to process form submissions before output.
load-{$hook_suffix} - /
remove_menu_page( $slug )to hide entries.remove_submenu_page( $parent, $slug )
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 )| 辅助函数 | 父级页面 |
|---|---|
| 仪表盘 |
| 文章 |
| 媒体 |
| 页面 |
| 评论 |
| 外观 |
| 插件 |
| 用户 |
| 工具 |
| 设置 |
- 钩子:
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; corrupts layout.
echo - Prefix names -- use a unique prefix to avoid collisions.
- Escape output -- all attribute values through /
esc_attr().esc_html() - Pass to
$tagto enable theshortcode_atts()filter.shortcode_atts_{$tag}
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- Verify nonce with
wp_verify_nonce() - Check
DOING_AUTOSAVE - Check
current_user_can( 'edit_post', $post_id ) - 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- 使用验证随机数
wp_verify_nonce() - 检查状态
DOING_AUTOSAVE - 检查权限
current_user_can( 'edit_post', $post_id ) - 在调用前对输入内容进行清理
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: , , (required for Block Editor), , , , .
publichas_archiveshow_in_restsupportsrewritemenu_iconcapability_type | Feature Enabled |
|---|---|
| Title field |
| Content editor |
| Featured image |
| Excerpt field |
| Revision history |
| Template + menu order |
| Custom fields meta box |
| Comments |
Key taxonomy args: (true = categories, false = tags), , , .
hierarchicalshow_in_restrewriteshow_admin_column| Template File | When |
|---|---|
| Single CPT post |
| CPT archive |
| Custom taxonomy archive |
| Specific term archive |
- Hook on . Flush rewrite rules on activation only -- never on every request.
init
php
register_post_type( $post_type, $args )
register_taxonomy( $taxonomy, $object_type, $args )关键CPT参数: , , (区块编辑器必填), , , , .
publichas_archiveshow_in_restsupportsrewritemenu_iconcapability_type | 启用的功能 |
|---|---|
| 标题字段 |
| 内容编辑器 |
| 特色图片 |
| 摘要字段 |
| 修订历史 |
| 模板 + 菜单顺序 |
| 自定义字段元框 |
| 评论 |
关键分类法参数: (true = 分类,false = 标签), , , .
hierarchicalshow_in_restrewriteshow_admin_column| 模板文件 | 适用场景 |
|---|---|
| 单个CPT文章 |
| CPT归档页面 |
| 自定义分类归档页面 |
| 特定术语归档页面 |
- 在钩子上注册。仅在激活时刷新重写规则 -- 不要在每次请求时都执行。
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 )| Argument | Default | Notes |
|---|---|---|
| | Or |
| | Seconds. Increase for slow APIs. |
| | Max redirects to follow. |
| | Use |
| | Never disable in production. |
| | |
- 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 )| 参数 | 默认值 | 说明 |
|---|---|---|
| | 可选值: |
| | 秒数。针对响应缓慢的API可适当增加。 |
| | 最大重定向次数。 |
| | 启用长连接请使用 |
| | 生产环境绝对不要禁用。 |
| | |
- 使用/
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 to add entries like .
cron_schedulesarray( 'interval' => 300, 'display' => 'Every 5 Minutes' )Rules:
- Always guard with before scheduling.
wp_next_scheduled() - Clean up with in
wp_unschedule_event().register_deactivation_hook - For production: + system crontab running
define( 'DISABLE_WP_CRON', true ).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_schedulesarray( '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 with
add_meta_box()screen and'dashboard'context.'side' - 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 , , , , .
roleorderbyordernumbermeta_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: 支持, , , , 参数。
roleorderbyordernumbermeta_query- 角色会持久化存储在数据库中 -- 在激活时添加,卸载时移除。
9. Privacy API
9. 隐私API
WordPress 4.9.6+ GDPR/privacy tools. Plugins storing personal data should register exporters and erasers.
Filters:
- -- register exporter callback returning
wp_privacy_personal_data_exporters.array( 'data' => [...], 'done' => bool ) - -- register eraser callback returning
wp_privacy_personal_data_erasers.array( 'items_removed' => int, 'items_retained' => int, 'messages' => [], 'done' => bool )
Privacy policy: on .
wp_add_privacy_policy_content( $plugin_name, $policy_text )admin_init- Use parameter and
$pagefor large datasets.'done' => false
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_initwp_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 | | |
|---|---|---|
| Scope | Per-theme | Global (all themes) |
| Switching themes | Reverts to new theme's values | Persists |
| Storage | Single | Individual option rows |
| Customizer default | Yes ( | Must set |
| Filter | | |
Use for visual/display settings. Use for functional plugin settings.
theme_modoptionphp
set_theme_mod( $name, $value )
get_theme_mod( $name, $default )
remove_theme_mod( $name )
get_theme_mods()| 特性 | | |
|---|---|---|
| 作用范围 | 按主题划分 | 全局(所有主题共享) |
| 切换主题时 | 恢复为新主题的默认值 | 保持不变 |
| 存储方式 | 单个 | 独立的选项行 |
| 自定义器默认支持 | 是( | 必须设置 |
| 过滤器 | | |
视觉/显示设置使用,功能性插件设置使用。
theme_modoption11. Site Health API
11. 站点健康API
Custom tab: filter , action .
site_health_navigation_tabssite_health_tab_contentCustom status test: filter with .
site_status_tests$tests['direct']['key'] = array( 'label' => ..., 'test' => $callback )Test callback returns: , (good | recommended | critical), (label + color), , , .
labelstatusbadgedescriptionactionstestDebug info: filter to add fields under .
debug_information$info['plugin-slug']['fields']自定义标签页: 使用过滤器和动作。
site_health_navigation_tabssite_health_tab_content自定义状态测试: 使用过滤器,格式为。
site_status_tests$tests['direct']['key'] = array( 'label' => ..., 'test' => $callback )测试回调返回内容包含: , (good | recommended | critical), (标签+颜色), , , 。
labelstatusbadgedescriptionactionstest调试信息: 使用过滤器在下添加字段。
debug_information$info['plugin-slug']['fields']12. Global Variables
12. 全局变量
Inside the Loop
循环内部
| Variable | Type | Description |
|---|---|---|
| | Current post being processed |
| | Current post's author |
| | Current page of a paginated post |
| | Whether post has |
| | Total pages in paginated post |
| | Whether to show content past |
| 变量 | 类型 | 描述 |
|---|---|---|
| | 当前正在处理的文章 |
| | 当前文章的作者 |
| | 分页文章的当前页码 |
| | 文章是否包含 |
| | 分页文章的总页数 |
| | 是否显示 |
Core Objects
核心对象
| Variable | Type | Preferred API |
|---|---|---|
| | No alternative -- use directly |
| | Template tags: |
| | |
| | |
| | |
| | |
| 变量 | 类型 | 推荐使用的API |
|---|---|---|
| | 无替代方案 -- 直接使用 |
| | 模板标签: |
| | |
| | |
| | |
| | |
Admin & Version
后台与版本
| Variable | Type | Description |
|---|---|---|
| | Current admin page filename |
| | Current post type in admin screens |
| | WordPress version number |
| | Database schema version |
| 变量 | 类型 | 描述 |
|---|---|---|
| | 当前后台页面的文件名 |
| | 后台屏幕中当前的文章类型 |
| | WordPress版本号 |
| | 数据库架构版本 |
Server Detection
服务器检测
| Variable | Type | True when... |
|---|---|---|
| | Running on Apache |
| | Running on Nginx |
| | Running on IIS |
| 变量 | 类型 | 为true的场景 |
|---|---|---|
| | 运行在Apache服务器上 |
| | 运行在Nginx服务器上 |
| | 运行在IIS服务器上 |
Best Practices
最佳实践
- Use API functions first -- instead of
get_queried_object().global $wp_query; $wp_query->get_queried_object() - Always declare before use:
globalglobal $wpdb; - Never modify without
$postafterward.wp_reset_postdata() - is the exception -- it has no wrapper and must be used directly for custom queries.
$wpdb
- 优先使用API函数 -- 例如使用代替
get_queried_object()。global $wp_query; $wp_query->get_queried_object() - 使用前必须声明-- 例如
globalglobal $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:
- -- override
wp_calculate_image_sizesattribute for your layout.sizes - -- modify source list (e.g., remove oversized sources).
wp_calculate_image_srcset - -- cap max width in srcset (default 2048px).
max_srcset_image_width
WordPress 5.5+ adds automatically. Pass for above-the-fold images.
loading="lazy"'loading' => 'eager'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 - -- 限制srcset中的最大宽度(默认2048px)。
max_srcset_image_width
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.| Function | Returns |
|---|---|
| Number of times an action has fired (int). |
| Whether a specific action is currently running. |
| Whether a specific filter is currently running. |
| Name of the action currently being executed. |
| Name of the current filter (works for actions). |
| Whether a callback is registered for an action. |
| Whether a callback is registered for a filter. |
Rules:
- Removal must happen after the original and at the same priority.
add_action() - Use guard to prevent recursive triggers in
did_action() > 1.save_post - Prefix all custom hook names. Document with /
@since. Never change signatures after release.@param
php
remove_action( $hook, $callback, $priority )
remove_filter( $hook, $callback, $priority )
do_action( $hook, ...$args ) // 触发自定义动作。
apply_filters( $hook, $value, ...$args ) // 触发自定义过滤器。| 函数 | 返回值 |
|---|---|
| 动作触发的次数(整数)。 |
| 是否正在执行特定动作。 |
| 是否正在执行特定过滤器。 |
| 当前正在执行的动作名称。 |
| 当前的过滤器名称(也适用于动作)。 |
| 是否为某个动作注册了回调函数。 |
| 是否为某个过滤器注册了回调函数。 |
规则:
- 移除动作必须在原之后执行,且优先级必须一致。
add_action() - 在中使用
save_post防止递归触发。did_action() > 1 - 所有自定义钩子名称添加前缀。使用/
@since注释文档。发布后不要修改参数签名。@param
15. Common Mistakes
15. 常见错误
| Mistake | Fix |
|---|---|
| Flushing rewrite rules on every request | Only flush on activation: |
Registering CPTs/taxonomies in | Use |
| Always |
| Saving meta without nonce/capability check | Verify nonce, check |
Scheduling cron without | Always check first or you create duplicate events |
| Not cleaning up cron on deactivation | |
Using | Use |
Disabling | Only disable for local development; never in production |
| Adding roles/caps on every page load | Roles persist in DB -- add on activation, remove on uninstall |
Forgetting | Required for Block Editor and REST API access |
| Not paginating privacy exporters/erasers | Set |
Calling | Must run after the original |
Using | Use |
Modifying | Always call |
Hardcoding image sizes in | Use |
| CPT slug matches a page slug | Individual CPT posts 404 -- use a different rewrite slug or rename the page |
| Default is 1 arg -- pass |
Filters that | Filter callbacks MUST return the modified value; echoing corrupts output |
| 错误 | 修复方案 |
|---|---|
| 每次请求都刷新重写规则 | 仅在激活时刷新: |
在 | 使用 |
短代码处理函数中使用 | 始终返回HTML字符串 |
| 保存元数据时未验证随机数/权限 | 验证随机数,检查 |
调度Cron任务时未使用 | 必须先检查,否则会创建重复任务 |
| 停用插件时未清理Cron任务 | 在 |
使用 | 使用 |
生产环境禁用 | 仅在本地开发时禁用;生产环境绝对不要禁用 |
| 每次页面加载都添加角色/权限 | 角色持久化存储在数据库中 -- 激活时添加,卸载时移除 |
自定义文章类型未设置 | 区块编辑器和REST API访问必填 |
| 隐私导出器/擦除器未分页 | 设置 |
过早调用 | 必须在原 |
使用 | 使用 |
修改 | 自定义循环后必须调用 |
在 | 使用 |
| 自定义文章类型slug与页面slug冲突 | 单个CPT文章会返回404 -- 使用不同的重写slug或重命名页面 |
| 默认仅传递1个参数 -- 需要传入 |
过滤器函数使用 | 过滤器回调必须返回修改后的值;使用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 -- 主题修改、站点健康、响应式图片和高级钩子的完整代码示例