Function Friday #4: add conditional classes to the body tag
Every Friday, I’m sharing code snippets that I use to customize WordPress. Feedback/suggestions are always welcome! For more information, check out the first post in the series.
If you haven’t spent time looking at WordPress starter/default themes, you may not have come across the body_class function before. Adding it to your body tag, like this:
<body <?php body_class(); ?>>
will output something like this (depending on what kind of content you’re viewing):
<body class="home page-template-default page page-id-1">
This can be useful right out of the box for styling different types of content, but you can also conditionally add classes to this list for further styling.
The code
// Add extra classes to the body
function drollic_class_names( $classes ) {
global $post;
if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'gallery' ) ) {
$classes[] = 'has-gallery';
}
return $classes;
}
add_filter( 'body_class', 'drollic_class_names' );
This code grabs the post object and (after making sure it actually is a post object) uses the function has_shortcode to check for the presence of a particular shortcode. In this case, if it contains at least one instance of the gallery shortcode, the class “has-gallery” will be added to the array of classes output by body_class().
If you visit a page with a gallery, the body tag will now look something like this:
<body class="home page-template-default page page-id-1 has-gallery">
You can use any of WordPress’s conditional tags within this function. As another example, you could add a special class to any content that has a featured image:
// Add extra classes to the body
function drollic_class_names( $classes ) {
if( has_post_thumbnail() ) {
$classes[] = 'has-featured-image';
}
return $classes;
}
add_filter( 'body_class', 'drollic_class_names' );
As always, remember to add a unique prefix to your function names (like I’ve done with drollic) to avoid plugin/core conflicts.
Where does it go?
Because this adds classes that are (presumably) going to be styled by the theme, this should go in your theme’s functions file. There’s more info on this in the first Function Friday post.
Resources
- body_class function in the WordPress Code Reference
- has_shortcode function in the WordPress Code Reference
- has_post_thumbnail in the WordPress Code Reference
- is_a in the PHP manual
Leave a Reply