Adding a custom body class to the WordPress frontend can be useful when you want to add specific styling or functionality based on the current page or post being viewed. Here’s how you can add a custom body class to the WordPress frontend:
function wpsnippets_body_class( $classes ) {
// Type casting to make sure we have an array
$classes = (array) $classes;
// Add a custom class
$classes[] = 'my-custom-class';
return $classes;
}
add_filter('body_class', 'wpsnippets_body_class');
This code snippet will add my-custom-class
to the class
of the <body>
.
Add custom body class conditionally
If the custom class you want to add to the body depends on the page that’s being viewed (for example), you can conditionally add specific classes to the <body>
, like so:
function wpsnippets_body_class( $classes ) {
// Type casting
$classes = (array) $classes;
// Add custom classes based on the current page or post being viewed.
if ( is_page() ) {
$classes[] = 'custom-page-class';
} elseif ( is_single() ) {
$classes[] = 'custom-single-class';
} elseif ( is_archive() ) {
$classes[] = 'custom-archive-class';
} elseif ( is_search() ) {
$classes[] = 'custom-search-class';
} elseif ( is_404() ) {
$classes[] = 'custom-error-404-class';
}
return $classes;
}
add_filter('body_class', 'wpsnippets_body_class');
This code uses the body_class
filter to add custom classes to the body
tag on the frontend. It checks the type of page being viewed (page, post, archive, search, or 404 page) and adds a corresponding custom class. You can modify the code to add your own custom classes based on your specific needs.
That’s it! Now, when you view a page or post on the frontend, the body
tag will have a custom class based on the type of page being viewed.
Please note: Your site’s active theme needs to use the body_class()
function, like so:
<body <?php body_class(); ?>>
If your theme doesn’t use this function, the above snippets will not work and you will have to add the classes manually, editing theme files directly (not recommended, however).