add_pages_page()
云策文档标注
概述
add_pages_page() 函数用于在 WordPress 后台的“页面”主菜单下添加一个子菜单页面。它是 add_submenu_page() 的包装函数,简化了向页面菜单添加子页面的过程。
关键要点
- 函数功能:向“页面”主菜单添加子菜单页面,基于用户权限控制显示。
- 参数说明:包括 $page_title(页面标题)、$menu_title(菜单标题)、$capability(所需权限)、$menu_slug(唯一标识符)、$callback(回调函数)和 $position(菜单位置)。
- 返回值:返回页面的 hook_suffix 或 false(如果用户权限不足)。
- 使用时机:必须在 admin_menu 钩子中调用,避免过早触发权限错误。
- 内部实现:通过调用 add_submenu_page() 并指定父菜单为 'edit.php?post_type=page' 来实现。
代码示例
function wpdocs_my_plugin_menu() {
add_pages_page( __( 'My Plugin Pages', 'textdomain' ), __( 'My Plugin', 'textdomain' ), 'read', 'my-unique-identifier', 'my_plugin_function');
}
add_action( 'admin_menu', 'wpdocs_my_plugin_menu' );注意事项
- 权限检查:回调函数必须验证用户是否具有 $capability 指定的权限。
- 钩子顺序:避免在 admin_menu 钩子之前调用,否则可能导致权限错误消息。
- 版本兼容性:$position 参数从 WordPress 5.3.0 开始支持。
原文内容
Adds a submenu page to the Pages 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_pages_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'edit.php?post_type=page', $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):
function wpdocs_my_plugin_menu() { add_pages_page( __( 'My Plugin Pages', 'textdomain' ), __( 'My Plugin','textdomain' ), 'read', 'my-unique-identifier', 'my_plugin_function'); } add_action( 'admin_menu', 'wpdocs_my_plugin_menu' );