Body Class Control in WordPress

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 );

Comments

2 responses to “Body Class Control in WordPress”

  1. Bronson Quick Avatar

    Haha I love both: “To call my coding opinionated is somewhat of an understatement” and “fussy behaviour from people like me” :)

    How’s the new site design coming along Sir?

    1. Peter Wilson Avatar
      Peter Wilson

      It’s coming alone nicely. I am putting it into a WP theme & hope to get it launched in the next week or two.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.