add_posts_page()
云策文档标注
概述
add_posts_page() 函数用于在 WordPress 后台的“文章”主菜单下添加一个子菜单页面。它是 add_submenu_page() 的包装函数,简化了向文章菜单添加子页面的过程。
关键要点
- 函数基于用户角色和能力(capability)控制菜单显示,输出处理函数需验证用户权限。
- 参数包括页面标题、菜单标题、能力要求、菜单 slug、回调函数和位置,其中 $position 参数从 5.3.0 版本开始支持。
- 必须在 admin_menu 钩子中调用,过早挂钩可能导致权限错误。
- 返回值为页面 hook_suffix 或 false(用户无权限时)。
代码示例
/**
* Adds a submenu item to the "Posts" menu in the admin.
*/
function wpdocs_my_plugin_menu() {
add_posts_page(
__( 'My Plugin Posts Page', 'textdomain' ),
__( 'My Plugin', 'textdomain' ),
'read',
'my-unique-identifier',
'wpdocs_my_plugin_function'
);
}
add_action( 'admin_menu', 'wpdocs_my_plugin_menu');注意事项
- 确保在 admin_menu 钩子中调用,避免权限错误。
- 回调函数应检查用户能力,以增强安全性。
原文内容
Adds a submenu page to the Posts main menu.
Description
This function takes a capability which will be used to determine whether or not a page is included in the menu.
The function which is hooked in to handle the output of the page must check that the user has the required capability as well.
Parameters
$page_titlestringrequired-
The text to be displayed in the title tags of the page when the menu is selected.
$menu_titlestringrequired-
The text to be used for the menu.
$capabilitystringrequired-
The capability required for this menu to be displayed to the user.
$menu_slugstringrequired-
The slug name to refer to this menu by (should be unique for this menu).
$callbackcallableoptional-
The function to be called to output the content for this page.
$positionintoptional-
The position in the menu order this item should appear.
Default:
null
Source
function add_posts_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'edit.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
Skip to note 2 content
Codex
Example
Typical usage occurs in a function registered with the ‘
admin_menu‘ hook (see Adding Administration Menus):/** * Adds a submenu item to the "Posts" menu in the admin. */ function wpdocs_my_plugin_menu() { add_posts_page( __( 'My Plugin Posts Page', 'textdomain' ), __( 'My Plugin', 'textdomain' ), 'read', 'my-unique-identifier', 'wpdocs_my_plugin_function' ); } add_action( 'admin_menu', 'wpdocs_my_plugin_menu');