wp_admin_bar_render()
概述
wp_admin_bar_render() 函数用于渲染 WordPress 管理工具栏到页面,基于 $wp_admin_bar->menu 成员变量。它通过 'wp_body_open' 和 'wp_footer' 动作钩子确保兼容性,并提供了 'admin_bar_menu' 等钩子供开发者自定义工具栏菜单。
关键要点
- 函数在 'wp_body_open' 动作早期调用,优先渲染管理工具栏,同时通过 'wp_footer' 作为回退以兼容旧主题。
- 使用 'admin_bar_menu' 动作钩子可以添加、移除或修改管理工具栏项,访问 $post 等全局变量。
- 函数包含 'wp_before_admin_bar_render' 和 'wp_after_admin_bar_render' 钩子,分别在渲染前后触发。
- 通过静态变量 $rendered 防止重复渲染,并检查 is_admin_bar_showing() 和 $wp_admin_bar 对象有效性。
代码示例
function wp_admin_bar_render() {
global $wp_admin_bar;
static $rendered = false;
if ( $rendered ) {
return;
}
if ( ! is_admin_bar_showing() || ! is_object( $wp_admin_bar ) ) {
return;
}
do_action_ref_array( 'admin_bar_menu', array( &$wp_admin_bar ) );
do_action( 'wp_before_admin_bar_render' );
$wp_admin_bar->render();
do_action( 'wp_after_admin_bar_render' );
$rendered = true;
}注意事项
- 从 WordPress 5.4.0 开始,优先在 'wp_body_open' 动作调用,'wp_footer' 作为回退,确保向前兼容。
- 使用 'admin_bar_menu' 钩子时,优先级影响新项位置,修改现有项需高优先级或使用 'wp_before_admin_bar_render'。
- 函数依赖于 WP_Admin_Bar 类和 is_admin_bar_showing() 函数,确保环境正确设置。
Renders the admin bar to the page based on the $wp_admin_bar->menu member var.
Description
This is called very early on the ‘wp_body_open’ action so that it will render before anything else being added to the page body.
For backward compatibility with themes not using the ‘wp_body_open’ action, the function is also called late on ‘wp_footer’.
It includes the ‘admin_bar_menu’ action which should be used to hook in and add new menus to the admin bar. This also gives you access to the $post global, among others.
Source
function wp_admin_bar_render() {
global $wp_admin_bar;
static $rendered = false;
if ( $rendered ) {
return;
}
if ( ! is_admin_bar_showing() || ! is_object( $wp_admin_bar ) ) {
return;
}
/**
* Loads all necessary admin bar items.
*
* This hook can add, remove, or manipulate admin bar items. The priority
* determines the placement for new items, and changes to existing items
* would require a high priority. To remove or manipulate existing nodes
* without a specific priority, use `wp_before_admin_bar_render`.
*
* @since 3.1.0
*
* @param WP_Admin_Bar $wp_admin_bar The WP_Admin_Bar instance, passed by reference.
*/
do_action_ref_array( 'admin_bar_menu', array( &$wp_admin_bar ) );
/**
* Fires before the admin bar is rendered.
*
* @since 3.1.0
*/
do_action( 'wp_before_admin_bar_render' );
$wp_admin_bar->render();
/**
* Fires after the admin bar is rendered.
*
* @since 3.1.0
*/
do_action( 'wp_after_admin_bar_render' );
$rendered = true;
}
Hooks
- do_action_ref_array( ‘admin_bar_menu’, WP_Admin_Bar $wp_admin_bar )
-
Loads all necessary admin bar items.
- do_action( ‘wp_after_admin_bar_render’ )
-
Fires after the admin bar is rendered.
- do_action( ‘wp_before_admin_bar_render’ )
-
Fires before the admin bar is rendered.