body_class()
云策文档标注
概述
body_class() 是 WordPress 模板标签,用于输出 body 元素的 class 属性值,通常放置在主题的 header.php 文件中。它基于当前页面类型(如文章、页面、归档等)自动生成一系列 CSS 类,便于开发者进行样式定制。
关键要点
- body_class() 函数输出 body 元素的 class 属性,参数 $css_class 可选,用于添加额外的类名(字符串或数组)。
- 默认生成的类包括静态类(如 .home、.archive、.logged-in)和动态类(如 .page-id-2、.category-{id}),具体取决于页面上下文。
- 可以通过 'body_class' 过滤器添加、修改或移除类,例如使用 add_filter('body_class', 'custom_function') 来自定义类数组。
- 相关函数 get_body_class() 返回类名数组,esc_attr() 用于转义 HTML 属性。
代码示例
// 基本用法:在主题的 body 标签中调用
<body <?php body_class(); ?>>
// 添加额外类
<body <?php body_class('custom-class'); ?>>
// 通过过滤器添加类
add_filter('body_class', function($classes) {
$classes[] = 'new-class';
return $classes;
});
// 条件性添加类(针对特定页面模板)
add_filter('body_class', 'custom_body_class');
function custom_body_class($classes) {
if (is_page_template('page-example.php')) {
$classes[] = 'example';
}
return $classes;
}
// 移除类
add_filter('body_class', function($classes) {
if (in_array('class-to-remove', $classes)) {
unset($classes[array_search('class-to-remove', $classes)]);
}
return $classes;
});注意事项
- body_class() 直接输出 HTML,而 get_body_class() 返回数组,适用于需要进一步处理的情况。
- 使用过滤器时,注意优先级和数组键的处理,以确保正确添加或移除类。
- 动态类名基于 sanitize_html_class() 生成,确保安全性和兼容性。
原文内容
Displays the class names for the body element.
Parameters
$css_classstring|string[]optional-
Space-separated string or array of class names to add to the class list. Default empty.
Source
function body_class( $css_class = '' ) {
// Separates class names with a single space, collates class names for body element.
echo 'class="' . esc_attr( implode( ' ', get_body_class( $css_class ) ) ) . '"';
}
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
Skip to note 14 content
Drew Jaynes
Adding More Classes
By default, the only classes will be those described above.
To add more classes, the template tag’s parameter can be added. For example, to add a unique class to the same template used above:
<body <?php body_class( 'class-name' ); ?>>The results would be:
[html]
[/html]
Skip to note 15 content
Drew Jaynes
Add New Classes via Filter
You can add additional body classes by filtering the ‘body_class’ hook.
To add the following to the WordPress Theme functions.php file, changing my_class_names and class-name to meet your needs:
// Add specific CSS class by filter. add_filter( 'body_class', function( $classes ) { return array_merge( $classes, array( 'class-name' ) ); } );Skip to note 16 content
Sam Kent
Here’s a solution for adding a body class to a specific page template:
add_filter( 'body_class', 'custom_class' ); function custom_class( $classes ) { if ( is_page_template( 'page-example.php' ) ) { $classes[] = 'example'; } return $classes; }The result on the front-end:
<body class="page page-id-7 page-template page-template-page-example page-template-page-example-php example">add_filter( 'body_class', 'wpdocs_custom_class' ); function wpdocs_custom_class( $classes ) { if ( is_page_template( 'page-example.php' ) ) { array_push( $classes, 'example' ); } if ( wpdocs_another_function() ) { array_push( $classes, 'another' ); } return $classes; }Ifwpdocs_another_function()returnsTRUE, then this is the result on the front-end:body class="example another"Minor note: I’ve updated the arrays here to usearray_push()instead of using the short form array syntax e.g.$class[] = 'something', due to the updated WordPress Coding Standards for PHP arrays.Skip to note 17 content
maijabrazen
The above example about how to remove inline classes via filters is incorrect.
Here is the correct way to do it:
add_filter('body_class', function (array $classes) { if (in_array('class-to-remove', $classes)) { unset( $classes[array_search('class-to-remove', $classes)] ); } return $classes; });Skip to note 18 content
Mahesh Waghmare
# Function
body_class()add some STATIC classes depends on the page, post, archive, blog, search, 404 etc.# List of all default static classes which are added to
.rtl { /* # Checks if current locale is RTL (Right To Left script). */ } .home { /* # Depends on the site’s “Front page displays” Reading Settings ‘show_on_front’ and ‘page_on_front’. n If you set a static page for the front page of your site, this function will return true when viewing that page. */ } .blog { /* # Add if blog view homepage, otherwise false. */ } .archive { /* For # Month, Year, Category, Author, Post Type archive */ } .date { /* # For date archive */ } .search { /* # For search */ } .search-results { /* # If found posts in search result */ } .search-no-results { /* # If NOT found any posts in search result */ } .paged { /* # On paged result and not for the first page */ } .attachment { /* # On attachment page */ } .error404 { /* # On 404 page */ } .single { /* # Add for any post type, except {attachments} and {pages} */ } .single-format-standard { /* # standard post format */ } .post-type-archive { /* # post type archive page */ } .author { /* # author page */ } .category { /* # category page */ } .tag { /* # Tags page */ } .page { /* # existing single page */ } .page-parent { /* # Parent page only */ } .page-child { /* # Child page only */ } .page-template { /* # Page templates only */ } .page-template-default { /* # Default page templates only */ } .logged-in { /* # Logged in user */ } .admin-bar { /* # Only in admin bar */ } .no-customize-support { /* # Only in admin bar */ } .custom-background { /* # If theme support 'custom-background' or get_background_image() */ } .wp-custom-logo { /* # If the site has a custom logo. */ }# Function
body_class()also add some DYNAMIC classes as below:.single-/* sanitize_html_class($post->post_type, $post_id) */ .postid-/* $post_id */ .single-format-/* sanitize_html_class( $post_format ) */ .attachmentid-/* $post_id */ .attachment-/* str_replace( $mime_prefix, '', $mime_type ) */ .post-type-archive-/* sanitize_html_class( $post_type ) */ .author-/* sanitize_html_class( $author->user_nicename, $author->ID ) */ .author-/* $author->ID */ .category-/* $cat_class */ .category-/* $cat->term_id */ .tag-/* $tag_class */ .tag-/* $tag->term_id */ .tax-/* sanitize_html_class( $term->taxonomy ) */ .term-/* $term_class */ .term-/* $term->term_id */ .page-id-/* $page_id */ .parent-pageid-/* $post->post_parent */ .page-template-/* sanitize_html_class( str_replace( array( '.', '/' ), '-', basename( $part, '.php' ) ) ) */ .page-template-/* sanitize_html_class( str_replace( '.', '-', $template_slug ) ) */ .paged-/* $page */ .single-paged-/* $page */ .page-paged-/* $page */ .category-paged-/* $page */ .tag-paged-/* $page */ .date-paged-/* $page */ .author-paged-/* $page */ .search-paged-/* $page */ .post-type-paged-/* $page */You can check all these in function get_body_class()
Skip to note 19 content
Antonio Sanchez
To remove a class of the body_class function you have to do that:
add_filter( 'body_class', function( $classes ) { foreach($classes as $key => $class) { if( $class == "class-to-remove" ){ unset($classes[$key]); } } return $classes; }, 1000);The other functions mentioned above are not working since they are ignoring the keys of the array $classes and do not have the needed priority.
Skip to note 20 content
mahd1
Example: add a new class to
body.function wp_body_classes( $classes ) { $classes[] = 'class-name'; return $classes; } add_filter( 'body_class','wp_body_classes' );Skip to note 21 content
scott.hepler
This is from
get_page_template_slugas used by this function and is important to remember:If the template is stored in a Theme’s subdirectory (or a Parent Theme’s subdirectory of a Child Theme), the value of the wp_postmeta is both the folder and file names, e.g.:
my-templates/my-custom-template.phpSkip to note 22 content
akaygaur
// Add Body Class to your custom template add_filter( 'body_class', 'wpdocs_sp_body_class' ); function wpdocs_sp_body_class( $classes ) { $templates = array( 'custom-template-1.php', 'custom-template-2.php', 'custom-template-3.php' ); // add your custom template in array if ( is_page_template( $templates ) ) { $classes[] = 'your-custom-class'; // add your class here } return $classes; }Skip to note 23 content
gecko_guy
Add one custom body class to the entire site, as well as additional classes only where needed by conditionally targeting the page slugs.
In this example the site makes use of front end registration, login and password reset forms, so the goal is to modify the form styling only on these pages:
add_filter( 'body_class', function( $classes ) { if ( is_page( 'login' ) ) { $classes[] = 'login wtv-form'; } else { if ( is_page( 'register' ) ) { $classes[] = 'register wtv-form'; } else { if ( is_page( 'password-reset' ) ) { $classes[] = 'reset wtv-form'; } } } return array_merge( $classes, array( 'custom' ) ); } );Skip to note 24 content
m3lvin
Adding maijabrazen. Example if want remove author id from body class. If wish to remove Author name, use user_nicename
add_filter('body_class', function (array $classes) { $author = 'author-'.get_the_author_meta('ID') ; if (in_array($author, $classes)) { unset( $classes[array_search($author, $classes)] ); } return $classes; });Skip to note 25 content
Drew Jaynes
Remove Classes via Filters
Remove an existing body class by un-setting the key from the
$classesarray.// Removes a class from the body_class array. add_filter( 'body_class', function( $classes ) { if ( isset( $classes['class-to-remove'] ) ) { unset( $classes['class-to-remove'] ); } return $classes; } );Skip to note 26 content
Rinku Y
<body <?php body_class(); ?>>