add_theme_page()
云策文档标注
概述
add_theme_page() 函数用于在 WordPress 后台的 Appearance(外观)主菜单下添加一个子菜单页面。它是 add_submenu_page() 的包装函数,简化了主题相关页面的创建过程。
关键要点
- 函数本质上是 add_submenu_page() 的封装,固定 $parent_slug 为 'themes.php',从而将页面添加到 Appearance 菜单下。
- 参数包括 $page_title(页面标题)、$menu_title(菜单标题)、$capability(所需权限)、$menu_slug(菜单唯一标识符)、$callback(回调函数)和 $position(菜单位置)。
- 返回值是页面的 hook_suffix(成功时)或 false(用户无权限时)。
- 权限检查至关重要:$capability 参数控制菜单显示,回调函数也必须验证用户权限。
- 函数应在 'admin_menu' 钩子中调用,而非 'admin_init',以确保权限系统正常工作。
代码示例
function add_test_theme_page() {
add_theme_page( 'Theme Title Settings', 'Theme Menu Settings', 'edit_theme_options', 'test-theme-options', 'theme_option_page' );
}
add_action( 'admin_menu', 'add_test_theme_page' );
function theme_option_page() {
echo 'This is a test theme options page!';
}注意事项
- 确保 $menu_slug 唯一,避免与其他菜单冲突。
- 回调函数应包含权限验证逻辑,例如使用 current_user_can() 检查 $capability。
- 从 WordPress 5.3.0 开始支持 $position 参数,可用于自定义菜单位置。
原文内容
Adds a submenu page to the Appearance 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_theme_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $position = null ) {
return add_submenu_page( 'themes.php', $page_title, $menu_title, $capability, $menu_slug, $callback, $position );
}
Skip to note 2 content
johnnyhuy
This is from the WordPress Codex, which states that add_theme_page must be called early. Therefore, calling the function in the ‘admin_init’ hook will make role capabilities invalid in regard to theme page created.
Use the ‘admin_menu’ hook instead using an example as shown:
function add_test_theme_page() { add_theme_page( 'Theme Title Settings', 'Theme Menu Settings', 'edit_theme_options', 'test-theme-options', 'theme_option_page' ); } add_action( 'admin_menu', 'add_test_theme_page' ); function theme_option_page() { echo 'This is a test theme options page!'; }