Archived topic
Show Custom Body class on Pages and Posts
6 replies · Started by Giselle on January 31, 2022
Hi,
I've created a custom body class.
I added a snippet to get it to show on Pages and this is working. However, I need the class on Posts on Pages. I tried Tom's solution, but it isn't working:
https://generatepress.com/forums/topic/custom-css-body-class-field/
Can I add code to the below to show both?
THIS IS WORKING, BUT ONLY ON PAGES
add_filter( 'body_class', 'custom_body_class' );
/**
* Add custom field body class(es) to the body classes.
*
* It accepts values from a per-page custom field, and only outputs when viewing a singular static Page.
*
* @param array $classes Existing body classes.
* @return array Amended body classes.
*/
function custom_body_class( array $classes ) {
$new_class = is_page() ? get_post_meta( get_the_ID(), 'body_class', true ) : null;
if ( $new_class ) {
$classes[] = $new_class;
}
return $classes;
}
Thanks for your help!
Giselle
Hi there,
Tom's method should still work.
For reference this is the code:
add_filter( 'body_class', 'tu_page_specific_body_class' );
function tu_page_specific_body_class( $classes ) {
if ( is_singular() && get_post_meta( get_the_ID(), 'page_class', true ) ) {
$classes[] = get_post_meta( get_the_ID(), 'page_class', true );
}
return $classes;
}
In that code there are 2 x lines that reference the Custom Field Name: page_class
You need to change them both to your specific custom field name
Hi David,
Thanks. Just tried it again and it isn't working.
There's a body class set on narrow Pages at the moment called 'text-column'. When I replace the snippet I had originally (the one just for Pages) with Tom's code, the pages with that class go full-width and you can see the body class isn't there.
I've left it like that for now so you can see.
Example page below.
Thanks!
Giselle
The class is to make full-width pages narrow I mean.
OK heres your original code - i made a modification so its for any page or post:
add_filter( 'body_class', 'custom_body_class' );
/**
* Add custom field body class(es) to the body classes.
*
* It accepts values from a per-page custom field.
*
* @param array $classes Existing body classes.
* @return array Amended body classes.
*/
function custom_body_class( array $classes ) {
$new_class = get_post_meta( get_the_ID(), 'body_class', true );
if ( $new_class ) {
$classes[] = $new_class;
}
return $classes;
}
Hi David,
Sorry, I missed this:
In that code there are 2 x lines that reference the Custom Field Name: page_class
You need to change them both to your specific custom field name
1. I tried this first. My class is called body_class. I changed it to page_class in case that was causing problems. Didn't work.
2. I then changed it back and tried your code and it's working!
Thanks so much! much appreciated.
Giselle
Glad to be of help!