Categories
Code

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

By Peter Wilson

Peter has worked on the web for twenty years on everything from table based layouts in the 90s to enterprise grade CMS development.

Peter’s a big fan of musical theatre and often encourages his industry colleagues to join him for a show or two in New York or in the West End.

2 replies on “Body Class Control in WordPress”

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.