Add your own classes with the body_class and post_class filters
body_class() and post_class() print a set of CSS classes that describe the current page and the current post: single, single-post, postid-42, logged-in, has-post-thumbnail, category-news and many more. They are useful for CSS, and two filters let you add classes of your own: a layout chosen in a custom field, the section of the site a page belongs to, a marker for featured posts.
Problem: The design needs classes that WordPress does not add: a layout from a custom field, the top parent page as a “section” class, a class for posts with a certain tag.
Solution: Add the classes in the body_class and post_class filters. Both receive the array of classes WordPress has built and must return it; post_class also gets the post ID.
body_class
<?php
add_filter( 'body_class', 'ha_body_classes' );
function ha_body_classes( $classes ) {
// A layout chosen in a custom field, e.g. "full" or "sidebar"
if ( is_singular() ) {
$layout = get_post_meta( get_queried_object_id(), 'ha_layout', true );
if ( $layout ) {
$classes[] = 'layout-' . sanitize_html_class( $layout );
}
}
// The top parent page as a section: section-services on all pages under "Services"
if ( is_page() ) {
$ancestors = get_post_ancestors( get_queried_object_id() );
$top_id = $ancestors ? end( $ancestors ) : get_queried_object_id();
$classes[] = 'section-' . sanitize_html_class( get_post_field( 'post_name', $top_id ) );
}
return $classes;
}
get_post_ancestors() returns the parents from the closest to the top, so end() is the top one. Use get_queried_object_id() in body_class: the filter runs in the header, outside the loop.
post_class
<?php
add_filter( 'post_class', 'ha_post_classes', 10, 3 );
function ha_post_classes( $classes, $class, $post_id ) {
if ( has_tag( 'featured', $post_id ) ) {
$classes[] = 'is-featured';
}
if ( ! has_post_thumbnail( $post_id ) ) {
$classes[] = 'no-thumbnail';
}
return $classes;
}
post_class() is called for every post in a list, so keep the filter cheap. Tag and thumbnail checks are fine: WordPress has already loaded terms and meta of the posts in the main query.
Removing classes
Classes can be removed as well, for example the many category-* and tag-* classes in post_class:
<?php
add_filter( 'post_class', function ( $classes ) {
return array_values( array_filter( $classes, function ( $class ) {
return 0 !== strpos( $class, 'tag-' );
} ) );
} );
Be careful with removing: plugins and the block editor styles may rely on classes like sticky, hentry or has-post-thumbnail. Remove only classes you know nobody uses.
NOTE: Pass every class that comes from data (a field, a slug) through sanitize_html_class(). It keeps only letters, digits, hyphens and underscores, so a value with a space or a quote cannot split into several classes or break out of the class attribute.