When you want to add custom styling to your WordPress website, you may want to add a CSS class to the body tag. This is a great way to easily apply a group of styles to all posts and pages.
This article will show you exactly how to add a CSS class to your body tag (body_class) to all posts and pages in WordPress.
function add_custom_body_class( $classes ) {
if ( is_singular() ) {
$classes[] = 'custom-body-class';
}
return $classes;
}
add_filter( 'body_class', 'add_custom_body_class' );
This code uses the body_class
filter hook to add a custom CSS class called “custom-body-class” to the body tag of all singular posts and pages. The is_singular()
function checks if the current page is a single post or page, and the $classes array stores the CSS classes that will be applied to the body tag.
To use this code, you can add it to your WordPress theme’s functions.php file or create a custom plugin. Once the code is in place, you can style the elements on your posts and pages using the “custom-body-class” CSS class.
You can also use this code to target specific pages:
function add_custom_body_class( $classes ) {
if ( is_page( 'about-us' ) || is_page( array( 5, 10, 15 ) ) || is_page( 'About Us' ) ) {
$classes[] = 'custom-body-class';
}
return $classes;
}
add_filter( 'body_class', 'add_custom_body_class' );
This code uses the is_page() function to check if the current page has a slug of “about-us,” an ID of 5, 10, or 15, or a title of “About Us,” and if it does, it adds a custom CSS class called “custom-body-class” to the body tag.
To target specific posts, use this function:
function add_custom_body_class( $classes ) {
if ( is_single( 'grandma-recipe' ) || is_single( array( 11, 54 ) ) || is_single( "My Grandma's Recipe" ) ) {
$classes[] = 'custom-body-class';
}
return $classes;
}
add_filter( 'body_class', 'add_custom_body_class' );