The issue may be that get_body_class() doesn’t print the classes but returns them in a string in case you want to save it into a variable. body_class() will print the classes which is probably what you want. You can then pass strings to the class or use a hook body_class in your functions.php to inject your own classes. Additionally, you need <?php opening and ?> closing tags. See the examples below:
Add classes to your body tag:
<body <?php body_class( array( 'additional-class', 'class-2' ) ); ?>>
Using a hook in functions.php to conditionally add classes to your body tag:
/**
* Modify the body class classes
*
* @param Array $classes - array of CSS class names
*
* @return Array $classes
*/
function theme_modify_body_classes( $classes ) {
// Additional classes to single posts
if( is_singular() && is_singular( 'post' ) ) {
$classes[] = 'singular-post';
}
return $classes;
}
add_action( 'body_class', 'theme_modify_body_classes' );
Finally, if you want your code example to work you can modify it as so:
<body <?php echo get_body_class() ?>>
– – – – –
Be careful using PHP – you can bring down your entire site if you mess something up with the strict syntax.
Thread Starter
ghoys
(@ghoys)
Is something like this?
function theme_modify_body_classes( $classes ) {
// Additional classes to single posts
if( is_single() && is_single( 'post-template-default', 'single', 'single-post', 'single-format-standard', 'custom-background', 'navbar-position-right'. 'header-position-left', 'custom-header', 'custom-header-image' ) ) {
$classes[] = 'single-post';
}
return $classes;
}
add_action( 'body_class', 'theme_modify_body_classes' );
Check the documentation on is_single() and is_singular(). Both those functions accept post types where it looks like you’re checking against templates.
If you want to add classes to single posts:
if( is_singular() && is_singular( 'post' ) ) { /* ... */ }
To add classes to categories:
if( is_category() && is_category( 'specific-category-slug' ) ) { /* ... */ }
WordPress has a whole list of conditional tags to help narrow down the specific page the user is viewing.
https://developer.wordpress.org/themes/basics/conditional-tags/