body_class() WordPress Function
The body_class() function is a Wordpress function that allows you to add classes to the body element of your site. This can be useful for adding custom styles to specific pages or for targeting specific pages with JavaScript.
body_class( string|string[] $class = '' ) #
Displays the class names for the body element.
Parameters
- $class
(string|string[])(Optional)Space-separated string or array of class names to add to the class list.
Default value: ''
More Information
This function gives the body element different classes and can be added, typically, in the header.php’s HTML body tag.
Basic Usage
The following example shows how to implement the body_class template tag into a theme.
<body <?php body_class(); ?>>
The actual HTML output might resemble something like this (the About the Tests page from the Theme Unit Test):
<body class="page page-id-2 page-parent page-template-default logged-in">
In the WordPress Theme stylesheet, add the appropriate styles, such as:
.page { /* styles for all posts within the page class */ } .page-id-2 { /* styles for only page ID number 2 */ } .logged-in { /* styles for all pageviews when the user is logged in */ }
Source
File: wp-includes/post-template.php
function body_class( $class = '' ) { // Separates class names with a single space, collates class names for body element. echo 'class="' . esc_attr( implode( ' ', get_body_class( $class ) ) ) . '"'; }
Expand full source codeCollapse full source codeView on TracView on GitHub
Changelog
Version | Description |
---|---|
2.8.0 | Introduced. |