I am trying to automatically add a class to my product <li element in a grid loop, depending on ACF Field value.
I have an ACF Field that is set by the client to decide wether the product background is blue or red. I would need to get the ACF Field color info (set by hex) and add it as a class to the product <li in another page loop.
The functions below could help but I'm not sur how to make them work.
add_filter('post_class', function($classes, $class, $product_id) {
if(is_product_category()) {
//only add these classes if we're on a product category page.
$classes = array_merge(['color-1','color-2'], $classes);
}
return $classes;
},10,3);
and
$fields = get_field_objects();
if( $fields ): ?>
<ul>
<?php foreach( $fields as $field ): ?>
<?php if( $field['value'] ): ?>
<li><?php echo $field['label']; ?>: <?php echo $field['value']; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
endif;
Is there a way to integrate this in my functions.php file and make it work somehow ?
Thanks for your help!
My Answer:
To add a class to a product in WooCommerce using Advanced Custom Fields (ACF), you can use the following code snippet:
php
function add_class_to_product($classes, $product_id) {
$custom_class = get_field('custom_class', $product_id);
if($custom_class) {
$classes[] = $custom_class;
}
return $classes;
}
add_filter('post_class', 'add_class_to_product', 10, 2);
In this code snippet, we are creating a function called `add_class_to_product` that retrieves the custom class field value using ACF's `get_field` function and adds it to the product's classes array. Then, we hook this function to the `post_class` filter to apply the custom class to the product.
Make sure to replace `'custom_class'` with the actual name of the ACF field you are using to store the custom class value. You can add this code to your theme's `functions.php` file or a custom plugin.
Rate this post
3 of 5 based on 2408 votesComments