body_class
Allows you to change the list of CSS classes assigned to the <body> tag.
This hook fires when the function of the same name, body_class(), is called. It must be called inside the <body <?php body_class( $class ) ?>> tag.
Usage
add_filter( 'body_class', 'wp_kama_body_class_filter', 10, 2 );
/**
* Function for `body_class` filter-hook.
*
* @param string[] $classes An array of body class names.
* @param string[] $css_class An array of additional class names added to the body.
*
* @return string[]
*/
function wp_kama_body_class_filter( $classes, $css_class ){
// filter...
return $classes;
}
- $classes(string[])
- An array of CSS classes that will be added to the
bodytag. - $class(string[])
- An array of additional CSS classes passed as a parameter to get_body_class( $class ) or body_class( $class ).
Examples
#1 Replace one class with another
A real-world example: an ad blocker applied display: none !important; to the body element because it had the single-ads class on single pages of the ads post type. Replace this “bad” class so the blocker does not react to it.
add_filter( 'body_class', 'remove_body_ads_class' );
function remove_body_ads_class( $classes ) {
foreach ( $classes as $index => $class ) {
if ( 'single-ads' === $class ) {
$classes[ $index ] = 'single-money';
}
}
return $classes;
}
Changelog
| Since 2.8.0 | Introduced. |
Where the hook is called
body_class
wp-includes/post-template.php 869
$classes = apply_filters( 'body_class', $classes, $css_class );