John Davidson

php - List all product attributes used in WooCommerce product category

0 comments
Message:


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.



My Answer:
php
$category_id = 123; // Replace with the ID of the product category

$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'product_cat' => 'category-slug', // Replace with the slug of the product category
);

$products = new WP_Query($args);

$attributes = array();

if ($products->have_posts()) {
while ($products->have_posts()) {
$products->the_post();
global $product;

$product_attributes = $product->get_attributes();

foreach ($product_attributes as $attribute) {
$attribute_name = $attribute->get_name();
$attributes[$attribute_name] = $attribute_name;
}
}
}

wp_reset_postdata();

// Output the list of attributes
echo '
    ';
    foreach ($attributes as $attribute) {
    echo '
  • ' . $attribute . '
  • ';
    }
    echo '
';


This code snippet retrieves all products in a specific category and then loops through each product to get its attributes. It then creates a list of unique attributes used in that category and outputs them in an unordered list. Make sure to replace the category ID and slug with the actual values in your WooCommerce setup.

Rate this post

4 of 5 based on 6411 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us