I'm trying to fetch specific product attributes from 'simple' products residing in specific categories. The attributes are numbers (pa_volume) and depending on what category the product is in, the attributes have different range. Like this:
Prod-cat 1: 20-145
Prod-cat 2: 60-200
Prod-cat 3: 100-300
I want these respective 'min' and 'max' values to show for each category in the loop.
Setup: I'm using Breakdance without a theme, storing all my custom code as a mu-plugin.
So, here's what I have so far.
/**
* Get min and max values for a specific product attribute within a single category
*
* @param string $attribute_name The taxonomy name (e.g., 'pa_size', 'pa_color')
* @param string $category_slug The category slug
* @return array Array with 'min' and 'max' values
*/
function get_attribute_value_range($attribute_name, $category_slug) {
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category_slug,
),
),
);
$product_ids = get_posts($args);
if (empty($product_ids)) {
return ['min' => 0, 'max' => 0];
}
$values = [];
foreach ($product_ids as $product_id) {
$product = wc_get_product($product_id);
if (!$product) {
continue;
}
// Get attribute value for this product
$attribute_value = $product->get_attribute($attribute_name);
// Skip if empty
if (empty($attribute_value)) {
continue;
}
// Handle comma-separated values (multiple values)
$attribute_values = explode(', ', $attribute_value);
foreach ($attribute_values as $value) {
// Convert to float if numeric
if (is_numeric($value)) {
$values[] = (float) $value;
}
}
}
// If no values found
if (empty($values)) {
return ['min' => 0, 'max' => 0];
}
return [
'min' => min($values),
'max' => max($values)
];
}
/**
* For use in Breakdance term loop - gets min/max values for the current term
*/
function get_category_attribute_range($term, $attribute_name) {
return get_attribute_value_range($attribute_name, $term->slug);
}
Then I call that function in a BD code block directly inside the builder like this:
<?php
// For Breakdance term loop, use the current term
global $breakdance_term_loop_item;
$current_term = $breakdance_term_loop_item;
$attribute_name = 'pa_volym';
// Get range for just this category
$range = get_category_attribute_range($current_term, $attribute_name);
echo $range['min'] . ' - ' . $range['max'];
?>
This however gets me 'min' and 'max' values from ALL products in the categories, disregarding the differences in range each category holds (remember the Prod-cat 1-3 example above).
How can I make this function take these differences in account?
Thank you