snippet 1 min read PHP 8.0+ WP 6.4+
A safer WordPress hook for body classes
Add a useful context class to the body element without coupling your theme to a page template.
#wordpress #php #snippet
WordPress gives us a clean filter for adding semantic context to the <body> element. This tiny hook makes CSS and client-side behavior easier to target while keeping the logic in one place.
The snippet
add_filter('body_class', function (array $classes): array { if (is_singular('product')) { $classes[] = 'is-product-single'; }
return $classes;});The callback receives the classes WordPress has already assembled, so we only append the context we need and return the complete array.
Why this holds up
- It uses the public
body_classextension point. - The type declaration makes the expected input and output obvious.
is_singular()keeps the class scoped to the relevant content type.
That last point matters: a hook should add context, not make every page carry assumptions about a single template.