Archived topic
Body Class for Pages & Posts Including An ACF Field
5 replies · Started by Jonathan on October 8, 2021
Hello,
I am trying to include an acf field into my body class function for posts (which is working well) and my php is failing to do this. What I have originally works for single posts:
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
if (is_single() ) {
global $post;
foreach((get_the_category($post->ID)) as $category
) {
$classes[] = $category->category_nicename;
}
}
return $classes;
}
If I add the acf field (checkbox for picking a colour to add to the body class) called 'border_page_colour' so that the acf field adds a colour class to the body for pages, it fails. i.e no class is set. The code I'm using is:
add_filter('body_class','add_category_to_single');
$value = get_field('border_page_colour'); // The ACF Field
function add_category_to_single($classes) {
if (is_singular() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
$classes[] = $category->category_nicename . $value;
}
}
elseif ( is_page() ) {
$classes[] = $value; // Supposed to take the ACF Field Value
}
return $classes;
}
Hi there,
you need to get the $value inside the function eg.
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
global $post;
$value = get_field('border_page_colour'); // The ACF Field
if (is_singular() ) {
foreach((get_the_category($post->ID)) as $category) {
$classes[] = $category->category_nicename . $value;
}
}
elseif ( is_page() ) {
$classes[] = $value; // Supposed to take the ACF Field Value
}
return $classes;
}
Also this condition elseif ( is_page() ) { will probably never be met. As is_singular() will return true if its a single page.
So would this work:
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
global $post;
$value = get_field('border_page_colour'); // The ACF Field
if ( is_page() ) {
$classes[] = $value; // Supposed to take the ACF Field Value
}
elseif (is_singular() ) {
foreach((get_the_category($post->ID)) as $category) {
$classes[] = $category->category_nicename . $value;
}
}
return $classes;
}
Ideally I want the page to condition to check if it is a Page then a Custom Post then a blog post.
In theory - yes
Thanks that works well.
Glad to hear that!