I'm currently making a header menu that lets people browse products in a certain product category, by the products' attributes (e.g., range, material).
I can't find a way to get a list of the product attributes used in a certain category, unless I go through each product in the category and note each unique attribute, as so:
<?php // Get all the products by the category. ?>
<?php $args = array(
'post_type' => 'product',
'post_status' => 'published',
'ignore_sticky_posts' => 1,
'tax_query' => array(
'taxonomy' => 'product_cat',
'terms' => 47, // The product Category itself.
'operator' => 'IN'
)); ?>
<?php // Get the list of matching posts, i.e., products in the category. ?>
<?php $products = ( new WP_Query($args) )->posts; ?>
<?php // An array of unique ranges found. ?>
<?php $ranges = []; ?>
<?php foreach ( $products as $product ): ?>
<?php // List of ranges attached to the current product. ?>
<?php $product_ranges = wc_get_product_terms( $product->ID, 'pa_range' ); ?>
<?php // This loop adds unseen ranges to the $ranges array. ?>
<?php foreach ( $product_ranges as $range ):?>
<?php if (! in_array($range->name, $ranges)): ?>
<?php array_push($ranges, $range->name); ?>
<?php endif; ?>
<?php endforeach; ?>
<?php endforeach; ?>
<?php print_r($ranges); ?>
The output of which looks like:
Array ( [0] => Urban [1] => Torque ... )
Which is correct, although this algorithm would be extremely slow with so many products.
I am hoping there is a better function that allows me to get all the unique attributes in a category.