- This topic has 5 replies, 2 voices, and was last updated 3 years, 11 months ago by
David.
-
AuthorPosts
-
October 8, 2021 at 2:56 am #1956842
Jonathan
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; }
October 8, 2021 at 4:47 am #1956921David
StaffCustomer SupportHi 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. Asis_singular()
will return true if its a single page.October 8, 2021 at 5:59 am #1956981Jonathan
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.
October 8, 2021 at 6:13 am #1956991David
StaffCustomer SupportIn theory – yes
October 8, 2021 at 6:43 am #1957011Jonathan
Thanks that works well.
October 8, 2021 at 8:13 am #1957278David
StaffCustomer SupportGlad to hear that!
-
AuthorPosts
- You must be logged in to reply to this topic.