钩子文档

show_admin_bar

💡 云策文档标注

概述

show_admin_bar 是一个 WordPress 过滤器,用于控制网站前端工具栏(原管理栏)的显示状态。它通过 is_admin_bar_showing() 函数实现,是隐藏工具栏的推荐方式。

关键要点

  • 过滤器名称:show_admin_bar,参数为布尔值 $show_admin_bar,默认 false。
  • 主要用途:切换网站前端工具栏的显示,无法在 WordPress 仪表盘中关闭。
  • 历史背景:自 WordPress 3.3 版本起,Admin Bar 更名为 Toolbar。
  • 相关函数:is_admin_bar_showing() 用于确定工具栏是否应显示。

代码示例

// 完全隐藏工具栏
add_filter( 'show_admin_bar', '__return_false' );

// 通过自定义函数隐藏工具栏
add_filter( 'show_admin_bar', 'my_function_admin_bar' );
function my_function_admin_bar() {
    return false;
}

// 仅对非管理员隐藏工具栏
add_filter( 'show_admin_bar', 'my_function_admin_bar' );
function my_function_admin_bar($show_admin_bar) {
    return ( current_user_can( 'administrator' ) ) ? $show_admin_bar : false;
}

注意事项

  • 代码应放在插件加载时或主题的 functions.php 文件中。
  • 用户显示偏好会影响已登录用户的工具栏显示。
  • 此过滤器自 WordPress 3.1.0 版本引入。

📄 原文内容

Filters whether to show the admin bar.

Description

Returning false to this hook is the recommended way to hide the admin bar.
The user’s display preference is used for logged in users.

Parameters

$show_admin_barbool
Whether the admin bar should be shown. Default false.

More Information

The show_admin_bar filter toggles the display status of the Toolbar for the front side of your website (you cannot turn off the toolbar on the WordPress dashboard anymore).

This filter is part of the function is_admin_bar_showing().

Note: The Admin Bar is replaced with the Toolbar since WordPress Version 3.3.

Source

$show_admin_bar = apply_filters( 'show_admin_bar', $show_admin_bar );

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Examples migrated from Codex.

    Note: The examples below should be called immediately upon plugin load or placed in theme’s functions.php file.

    This code would turn the display status of the Toolbar to off.

    add_filter( 'show_admin_bar', '__return_false' );

    Alternatively, you could write it into a full fledged function.

    add_filter( 'show_admin_bar' , 'my_function_admin_bar');
    function my_function_admin_bar() {
    	return false;
    }

    This would hide the Toolbar for all users except Administrators.

    add_filter( 'show_admin_bar' , 'my_function_admin_bar');
    function my_function_admin_bar($show_admin_bar) {
    	return ( current_user_can( 'administrator' ) ) ? $show_admin_bar : false;
    }