I like a much reduced set of body classes when coding up a WordPress theme. Two template types, two main classes.
Oh, and I put it on the HTML element too. To call my coding opinionated is somewhat of an understatement.
I like WordPress’s actions and filters for this reason, it keeps it accessible to new coders while allowing for fussy behaviour from people like me.
I’ll generally start with the code below and add classes if and when they are needed.
<?php
function pwcc_body_class( $classes, $custom_classes ) {
// I like to kill ALL the body classes!
$classes = [];
if ( is_home() || is_archive() ) {
$classes[] = 't-List';
// if ( 'post' == get_post_type() ) {
// $classes[] = 't-AllBlog';
// }
}
if ( is_search() ) {
$classes[] = 't-List';
}
if ( is_singular() || is_404() ) {
$classes[] = 't-Singular';
// if ( ( 'post' == get_post_type() ) || ( 'attachment' == get_post_type() ) ) {
// $classes[] = 't-AllBlog';
// }
}
// clearing classes removed the custom classes, redo.
// all the tidying & forcing the array has been done
$classes = array_merge( $classes, $custom_classes );
// escape the classes for attributes
$classes = array_map( 'esc_attr', $classes );
return $classes;
}
add_filter( 'body_class', 'pwcc_body_class', 10, 2 );
Leave a Reply