Useful Body Classes for Wordpress

Last modified May 15, 2021
.* :☆゚

WordPress is a super powerful CMS, and you can make it work even harder for you through the power of custom body classes. You can check against literally anything here, and generate classes based on any given condition, even acf fields.

Here are the most useful classes I keep by default in most of my own projects.

Simply paste in your functions file and modify as necessary.

function unicorn_tears_body_classes( $classes ) {

  // generate a class based on the current page template
  if ( is_page_template() ) {
    $classes[] = basename( get_page_template_slug(), '-template' );
  }

  //instead of targetting a page by id, I prefer to target a page by it's title so it is easier to modify in the visual admin.
  // This snippet will generate a class based on the title of the page or archive.
  $query = get_queried_object();
  if ( isset($query->slug)) {
    $classes[] = 'page-'.$query->slug;
  } else {
    $classes[] = 'page-'.$query->post_name;
  }

  //a body class that generates depending on the status of the post thumbnail
  //this is SUPER handy and honestly I don't know why this isn't built into WordPress already
  if ( has_post_thumbnail() ) {
    $classes[] = 'has-post-thumbnail';
  } else {
    $classes[] = 'missing-post-thumbnail';
  }

  // this is a really handy way to generate a class based on whether the user is browsing on a mobile or desktop device.
  //Note this is a WordPress function and may not be entirely foolproof for every use-case.
  // But it IS super handy because this is a PHP generated class which means it may be quicker to check against in any if conditions
  if ( wp_is_mobile() ) {
  $classes[] = 'is-touch';
  } else {
  $classes[] = 'no-touch';
  }

  return $classes;
}
add_filter( 'body_class', 'unicorn_tears_body_classes' );

Jaclyn Tan

I'm Jaclyn and I make websites. I aim to make the web a more fun and accessible place, sharing what I learn along the way.

My blog has no ads or sponsors and I plan on keeping it that way. If you like what I do please consider supporting me.