After years of faithfully building sites on Genesis and Beaver Theme going to a theme that has just what you need and no more has presenting the odd challenge or two.
Adding a custom body class is something that I’ve just expected to come already set up with a theme but it seems not. I’ll be creating a place here where I can leave all of my snippets of code for my own use in future but also it might just help out others too.
I needed to create a body class that a client could choose to add to a post in order to show or hide the featured image. When the class noimage was to be added the feature image wouldn’t show.
I started by enabling custom fields in my post preferences. You could also do this using Advanced Custom Fields.
I created a class called body_class in my post and gave it a value of noimage
I then added the following code to my theme funtions.php
add_filter( 'body_class', 'navitas_body_class' );
function navitas_body_class( array $classes ) {
$new_class = is_single() ? get_post_meta( get_the_ID(), 'body_class', true ) : null;
if ( $new_class ) {
$classes[] = $new_class;
}
return $classes;
}
And that’s it. There were so many over complicated versions of this around. I hope this help someone else out.