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: ''


Top ↑

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 */
}

Top ↑

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 ) ) ) . '"';
}


Top ↑

Changelog

Changelog
VersionDescription
2.8.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.