Home › Forums › Front-end Issues › Adding a classname to the body class
Hi there
We currently have a custom field called ‘brand’ and it is a Select field type.
The brand values are parkland, toro, pope, grillo, yamaha etc
We are using the body_class filter for inserting a brand value into the body class. We are using it within pages, products, product_cat, posts. We are using it to theme the page with different colours
Below is the function we have in functions.php
add_filter( 'body_class', 'brand_class' );
function brand_class( $classes ) {
if ( $brand = get_field( 'brand') ) {
$brand = esc_attr( trim( $brand ) );
$classes[] = $brand;
}
return $classes;
}
It has been working fine up until now but we have introduced a Product category that now includes different products with differing brands.
This product category page https://www.parkland.co.nz/products/parkland-pre-owned/ has the brand ‘parkland’ associated with it but the brand that is showing for the page is ‘toro’.
My question is how do I get the brand for the product_cat without it somehow getting the brand value from the product (assuming the first product in the list)
I hope I’ve explained myself clear enough
Cheers
Anthony
In the function ACF is assuming that the post you want to get the value from is the current post. In the case of a term it is probably getting the first post in the list.
The first thing that you need to do is to figure out what is actually being queried and then do something different and/or set the correct post ID.
// see what WP is actually showing.
$queried_object = get_queried_object();
if (is_a($queried_object, 'WP_Post')) {
// queried object is a post
$post_id = $queried_object->ID;
} elseif (is_a($queried_object, 'WP_Term')) {
// queried object is a term
$post_id = 'term_'$queried_object->term_id;
}
// and an acf field
$value = get_field('some_field_name', $post_id);
You can also do other things based on what type of object is being shown.
The topic ‘Adding a classname to the body class’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.