admin_body_class
云策文档标注
概述
admin_body_class 过滤器用于修改 WordPress 管理后台 body 标签的 CSS 类。它接收一个以空格分隔的字符串类名,而非数组,且某些核心类(如 wp-admin)不可移除。
关键要点
- 过滤器名称为 admin_body_class,用于管理后台 body 标签的 CSS 类。
- 参数 $classes 是一个以空格分隔的字符串,而非数组,与 post_class 和 body_class 过滤器不同。
- 核心类如 wp-admin、wp-core-ui 和 no-js 不可被移除或过滤。
- 添加新类时,应在类名前添加空格,避免与其他插件类名意外拼接。
- 可通过全局变量(如 $pagenow)判断当前页面,动态添加类。
代码示例
// 示例1:添加类时确保空格分隔
function admin_body_class( $classes ) {
// 错误:开头和结尾无空格
$classes .= 'my-class1 my-class2';
// 正确:添加前导和尾随空格
$classes .= ' my-class1 my-class2 ';
return $classes;
}
// 示例2:基于当前页面添加类
function wpdocs_admin_classes( $classes ) {
global $pagenow;
if ( in_array( $pagenow, array( 'post.php', 'post-new.php' ), true ) ) {
$classes .= ' your-class';
}
return $classes;
}
add_filter( 'admin_body_class', 'wpdocs_admin_classes' );注意事项
- 使用此过滤器时,注意 $classes 是字符串格式,操作时需处理空格分隔。
- 核心类不可移除,确保不影响管理后台的基础样式和功能。
原文内容
Filters the CSS classes for the body tag in the admin.
Description
This filter differs from the ‘post_class’ and ‘body_class’ filters in two important ways:
$classesis a space-separated string of class names instead of an array.- Not all core admin classes are filterable, notably: wp-admin, wp-core-ui, and no-js cannot be removed.
Parameters
$classesstring-
Space-separated list of CSS classes.
Source
$admin_body_classes = apply_filters( 'admin_body_class', '' );
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |
Skip to note 3 content
Philipp Stracker
When adding new classes to the body, you should make sure to add spaces before and after your class name. This prevents accidental concatenation of two plugins class-names.
Example:
function admin_body_class( $classes ) { // Wrong: No space in the beginning/end. $classes .= 'my-class1 my-class2'; // Right: Add a leading space and a trailing space. $classes .= ' my-class1 my-class2 '; return $classes; }Skip to note 4 content
thejaydip
If the current page is a post/page in edit mode
function wpdocs_admin_classes( $classes ) { global $pagenow; if ( in_array( $pagenow, array( 'post.php', 'post-new.php' ), true ) ) { $classes .= ' your-class'; } return $classes; } add_filter( 'admin_body_class', 'wpdocs_admin_classes' );