Filter Hook since 2.8.0

body_class

Filters the CSS classes on <body>

Description

body_class lets CSS target context without extra wrappers. Return the array — do not echo class names.

When it runs

When body_class() prints the body tag in the template.

Signature

apply_filters( 'body_class', string[] $classes, string[] $css_class );

Parameters

  • $classes string[] — Body class names.
  • $css_class string[] — Additional classes passed to body_class().

Examples

Basic

add_filter( 'body_class', function( $classes ) {
    if ( is_user_logged_in() ) {
        $classes[] = 'user-logged-in';
    }
    return $classes;
} );

Add a logged-in class for CSS and JS hooks.

Real case

add_filter( 'body_class', function( $classes ) {
    if ( is_singular( 'book' ) ) {
        $classes[] = 'book-' . get_post_field( 'post_name' );
    }
    return $classes;
} );

Add a slug-based class for per-book styling hooks.

Common Use Cases

  • Add role-based body classes
  • Target specific page templates via CSS
  • Add device detection classes
  • Inject A/B test variant classes

Common mistakes

  • Returning a string instead of the $classes array

Related hooks

FAQ

Can I remove a default body class instead of adding one?

Yes — search $classes with array_search() and unset() the key, then return the array.

Source: wp-includes/post-template.php

Group wizard

One session: this hook, then each related_hooks entry. Walk it and tell us what to change.

body_class → the_content

functions.php — body_class
functions.php
PHP body_class · Hook 1 of 2 · Step 1 of 7

Practice the body_class WordPress filter hook in our interactive sandbox — a VS Code-style editor with a step-by-step body_class tutorial, add_filter exercises, and instant feedback. No local WordPress install required.