wp_admin_bar_my_account_item()
云策文档标注
概述
wp_admin_bar_my_account_item() 函数用于在 WordPress 管理工具栏中添加“我的账户”项目,根据当前用户权限和站点配置动态生成链接和显示内容。
关键要点
- 函数接受一个 WP_Admin_Bar 实例作为必需参数,用于操作管理工具栏。
- 根据当前用户 ID 和权限(如 'read' 能力)确定个人资料编辑页面的 URL,支持单站点和多站点环境。
- 使用 wp_get_current_user() 获取用户显示名称,结合 get_avatar() 生成头像,并通过 WP_Admin_Bar::add_node() 方法添加节点到工具栏。
- 节点包含 ID、父级、标题(含问候语和头像)、链接和元数据(如 CSS 类和菜单标题)。
代码示例
function wp_admin_bar_my_account_item( $wp_admin_bar ) {
$user_id = get_current_user_id();
if ( ! $user_id ) {
return;
}
if ( current_user_can( 'read' ) ) {
$profile_url = get_edit_profile_url( $user_id );
} elseif ( is_multisite() ) {
$profile_url = get_dashboard_url( $user_id, 'profile.php' );
} else {
$profile_url = false;
}
/* translators: %s: Current user's display name. */
$howdy = sprintf( __( 'Howdy, %s' ), '' . wp_get_current_user()->display_name . '' );
$avatar = get_avatar( $user_id, 26 );
$wp_admin_bar->add_node(
array(
'id' => 'my-account',
'parent' => 'top-secondary',
'title' => $howdy . $avatar,
'href' => $profile_url,
'meta' => array(
'class' => empty( $avatar ) ? '' : 'with-avatar',
'menu_title' => wp_strip_all_tags( $howdy ),
'tabindex' => ( false !== $profile_url ) ? '' : 0,
),
)
);
}注意事项
- 函数在 WordPress 3.3.0 版本中引入,是核心功能的一部分。
- 如果用户未登录(get_current_user_id() 返回 0),函数会直接返回,不添加任何项目。
- 在多站点环境中,当用户没有 'read' 权限时,会使用 get_dashboard_url() 生成个人资料链接。
- 节点标题包含翻译后的问候语和头像,确保国际化支持。
原文内容
Adds the “My Account” item.
Parameters
$wp_admin_barWP_Admin_Barrequired-
The WP_Admin_Bar instance.
Source
function wp_admin_bar_my_account_item( $wp_admin_bar ) {
$user_id = get_current_user_id();
if ( ! $user_id ) {
return;
}
if ( current_user_can( 'read' ) ) {
$profile_url = get_edit_profile_url( $user_id );
} elseif ( is_multisite() ) {
$profile_url = get_dashboard_url( $user_id, 'profile.php' );
} else {
$profile_url = false;
}
/* translators: %s: Current user's display name. */
$howdy = sprintf( __( 'Howdy, %s' ), '<span class="display-name">' . wp_get_current_user()->display_name . '</span>' );
$avatar = get_avatar( $user_id, 26 );
$wp_admin_bar->add_node(
array(
'id' => 'my-account',
'parent' => 'top-secondary',
'title' => $howdy . $avatar,
'href' => $profile_url,
'meta' => array(
'class' => empty( $avatar ) ? '' : 'with-avatar',
'menu_title' => wp_strip_all_tags( $howdy ),
'tabindex' => ( false !== $profile_url ) ? '' : 0,
),
)
);
}
Changelog
| Version | Description |
|---|---|
| 3.3.0 | Introduced. |