Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

body_class

Filters the list of CSS classes on the <body> tag, so you can target specific pages from your stylesheet.

  • Type Filter
  • From WordPress
  • Since 2.8.0
  • Fired in wp-includes/post-template.php

When it fires

WordPress applies body_class when the theme calls body_class() on the tag. Classic themes do this in header.php and block themes get it automatically. It only runs on front-end pages.

The main query has run by then, so you can use conditional tags to decide which classes to add.

Parameters

Parameters
$classesstring[] An array of body class names.
$css_classstring[] An array of additional class names added to the body.

What to return

The array of class names. Add to it or remove from it, then return it.

Example: Add the page slug as a body class

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

Good to know

  • Always return the array. Returning nothing causes an error when the classes are printed.
  • The admin area has its own filter, admin_body_class, which works with a space-separated string, not an array.

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.