Search code examples
phpwordpresswoocommerceproducttaxonomy-terms

Filter by product attribute terms in a WooCommerce WC_Product_Query


I am trying to create a loop for products using WC_Product_Query. Now I want to filter them by Product Attributes.
Using WP Query it is possible to do this, with tax_query. But using WC_Product_Query it does not work.
(I do not want a WP_Query, because for products it is better to use WC_Product_Query)

<?php
$query = new WC_Product_Query(array(
    'limit' => 5,
    'orderby' => 'date',
    'order' => 'DESC',      
));

$products = $query->get_products();
$products = wc_products_array_orderby( $products, 'price', 'DESC' );

if (!empty($products)) :
    ?>
    <table>
    <?php
    foreach ($products as $product) :
        ?>
        <tr>
            <td><a href="<?php echo get_permalink($product->get_id()); ?>"><?php echo get_the_title($product->get_id()); ?></a></td>
            <td><?php echo get_the_post_thumbnail( $product->get_id(), 'thumbnail' ); ?></td>
            <td><?php echo $product->get_price(); ?></td>     
        </tr>
        <?php
    endforeach;
    ?> 
    </table>    
    <?php
endif;

Here's how to do it in WP Query:

$args = array(
    'post_type' => 'product',
    'tax_query' => array(
        array(
            'taxonomy' => 'pa_color',
            'field'    => 'slug',
            'terms'    => 'red',
        ),
    ),
);
$query = new WP_Query( $args );

Solution

  • Just as in a WP_Query, you can use a tax_query in a WC_Product_Query like:

    $query = new WC_Product_Query(array(
        'limit'     => 5,
        'orderby'   => 'date',
        'order'     => 'DESC',
        'tax_query' => array( array(
            'taxonomy' => 'pa_color',
            'field'    => 'slug',
            'terms'    => 'red',
        ) ),
    ) );
    
    $products = wc_products_array_orderby( $query->get_products(), 'price', 'DESC' );
    
    if ( ! empty($products) ) : ?>
        <table><?php
        // Products loop
        foreach ($products as $product) : ?>
            <tr>
                <td><a href="<?php echo get_permalink($product->get_id()); ?>"><?php echo get_the_title($product->get_id()); ?></a></td>
                <td><?php echo get_the_post_thumbnail( $product->get_id(), 'thumbnail' ); ?></td>
                <td><?php echo $product->get_price(); ?></td>
            </tr><?php
        endforeach; ?>
        </table><?php
    endif;
    

    Tested and works since WooCommerce version 3.