body_class( string|array $class = '' )

Display the classes for the body element.


Description #


Parameters #

$class

(string|array) (Optional) One or more classes to add to the class list.

Default value: ''


Top ↑

Source #

File: wp-includes/post-template.php

function body_class( $class = '' ) {
	// Separates classes with a single space, collates classes for body element
	echo 'class="' . join( ' ', get_body_class( $class ) ) . '"';
}


Top ↑

Changelog #

Changelog
Version Description
2.8.0 Introduced.

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 ↑

User Contributed Notes #

  1. Skip to note content
    Contributed by 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:

    <body class="page page-id-2 page-parent page-template-default logged-in class-name">
    
  2. Skip to note content
    Contributed by Drew Jaynes

    Remove Classes via Filters

    Remove an existing body class by un-setting the key from the $classes array.

    // 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;
    } );
    
  3. Skip to note content
    Contributed by Drew Jaynes

    Add New Classes via Filter

    You can add additional body classes by filtering the {@see ‘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' ) );
    } );
    

You must log in before being able to contribute a note.