Style Variation body class

Classic WordPress theme builders had the luxury of being able to target the body class for theme-specific styles. However, things have changed in the block theme era.

Gutenberg and WordPress core currently do not offer the means to output a body (or html) class currently, but may be in the future. For now, there is a workaround.

In your theme’s theme.json just add an entry to the styles.custom key and use the wp_get_global_settings() to grab the entry’s value and the body_class filter to add the current value as a class on the body element.

For example, in the Twenty Twenty-Three theme’s main theme.json you would do this:

{
	"$schema": "https://schemas.wp.org/trunk/theme.json",
	"version": 2,
	"settings": {
		"custom": {
			"variation": "default"
		}
	}
}

Then in a style variation, e.g. Whisper you can add:

{
	"$schema": "https://schemas.wp.org/trunk/theme.json",
	"version": 2,
	"settings": {
		"custom": {
			"variation": "whisper"
		}
	}
}

Now when you’re ready to add your body class you can use this:

function my_body_classes( $classes ) {
	$variation_class = wp_get_global_settings( array( 'custom', 'variation' ) );
	$classes[] = $variation_class;

	return $classes;
}
add_filter( 'body_class','my_body_classes' );

Which will give you a good old body.whisper class to target for your CSS.

Thanks to Lee Anthony for this clever workaround.