In this article, I’ll show you how to add a CSS class to the body tag using WordPress. Why would you want to add a class to the body element on your WordPress website? Well, WordPress has a comprehensive templating system and lets you create an infinite amount of posts and pages. It’s feasible you’d like to identify the body element by tagging it with a custom class name associated with a page slug or template name. In that case, here’s how you can add a custom CSS class to your WordPress site’s body tag.
WordPress PHP Function
The following PHP code snippet can be used inside of the function.php file of the active theme on your WordPress site.
function custom_body_class( $classes ) {
$classes[] = 'your-new-class';
return $classes;
}
add_filter('body_class', 'custom_body_class');
Explanation
By adding a filter to the body_class
hook you can manipulate the results. In the above example, I’ve created a custom function called custom_body_class(). It accepts 1 argument named $classes. $classes is an array that contains the preexisting CSS classes attached to the body element. Within the function, you can add, edit, or remove CSS classes.
More Examples
Add Body Class to Pages
You could add a new class to the body tag on pages using the slug of the current page.
function custom_body_class( $classes ) {
if ( is_page() ) {
$new_class = 'page--' . get_post_field( 'post_name', get_post() );
$classes[] = $new_class;
}
return $classes;
}
add_filter('body_class', 'custom_body_class');
Add Body Class to Custom Post Types
You could add a new class to the body tag of single pages for a particular custom post type.
function custom_body_class( $classes ) {
if ( is_singular('cpt-slug') ) {
$post_type = get_post_type();
$post_type_object = get_post_type_object($post_type);
$post_type_slug = $post_type_object->rewrite['slug'];
$new_class = 'cpt-' . $post_type_slug;
$classes[] = $new_class;
}
return $classes;
}
add_filter('body_class', 'custom_body_class');
Wrapping Up
WordPress offers a number of conditional tags. Using conditional logic, there’s an infinite amount of possible scenarios you could create for adding classes to your web page’s body element. How you do it remains relatively the same, but why you’re doing it is completely up to you.
0 Comments