Archived topic
Body class
13 replies · Started by Chad Biggs on April 14, 2017
How is the best way to add a body class for a specific page?
Hi Chad
Looking at the documentation it looks like we can use the following
add_filter( 'body_class','my_body_classes' );
function my_body_classes( $classes ) {
if ( is_shop() ) {
$classes[] = 'class-name';
$classes[] = 'class-name-two';
}
return $classes;
}
https://code.tutsplus.com/tutorials/adding-to-the-body-class-in-wordpress--cms-21077
Hope that works for you.
Yep, that's perfect :)
For a specific page, you would replace is_shop() with is_page( 'page-slug' )
Thank you Jamal and Tom.
Glad we could help :)
How would you add the page/post name (title) to the function so that you don't have to hard code the class?
i.e If I have an about page I would want the body to include .about as a class
Any reason you don't want to use the unique .page-id-xxx class that comes with each page?
It should work exactly the same.
Semantic reasons. The class .page-id-xxx is meaningless while I .about-us is clear.
I used this piece of code in functions.php of my child theme to make the class:
add_filter( 'body_class', 'sk_body_class_for_pages' );
function sk_body_class_for_pages( $classes ) {
if ( is_singular( 'page' ) ) {
global $post;
$classes[] = 'page-' . $post->post_name;
}
return $classes;
Awesome :)
Anyone know how to make a class based on the meta value? So if I create a custom field called 'my-body-class' and have a value of 'whatever is put in here' what do I need to show the value part?
Hi there,
try this:
<?php
function db_custom_field_body_class($classes) {
if(get_post_meta(get_the_ID(), 'custom_body_class', true))
$classes[] = get_post_meta(get_the_ID(), 'custom_body_class', true);
return $classes;
}
add_filter('body_class','db_custom_field_body_class');
?>
the custom field name is: custom_body_class or whatever you want to change it to.
Thanks. That worked well.
You're welcome