alexanderstanchev
alexanderstanchev

Reputation: 75

Woocommerce order products by attribute name asc

I have a custom page template with products in Woocommerce, but I want order the products by attribute's terms name asc. I have three terms. I don't know the right way to do it, I have tried this:

<?php
args = array(
     'post_type' => 'product',
     'posts_per_page' => 20,
     'meta_key' => 'pa_tire-type',
     'orderby'  => 'meta_value_num',
     'order'    => 'asc' 
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); 
global $product; ?>

Upvotes: 2

Views: 3215

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253814

— Updated —

You need to add a tax_query for your product attribute with the related terms (slugs) in it this way:

// Set HERE the attibute taxonomy slug
$taxonomy = 'pa_tire-type';

// Set HERE the term slugs for this attribute
$terms_array = array('term_slug1', 'term_slug2', 'term_slug3');

// The loop query
$loop = new WP_Query( array(
    'post_type'      => 'product',
    'posts_per_page' => 20,
    'post_status'    => 'publish',
    'tax_query'      => array( array(
            'taxonomy'  => $taxonomy,
            'field'     => 'slug',
            'terms'     =>  $terms_array,
            'operator'  => 'IN',
    ) ),
    'order_by'       => 'terms',
    'order'          => 'asc'
) );

$product_ids = array();

if ( $loop->have_posts() ): while ( $loop->have_posts() ) : $loop->the_post();
$product_ids[] = $loop->post->ID;
endwhile;

wp_reset_postdata();
endif;

// Testing output
print_pr($product_ids);

This code is tested and works.

Upvotes: 1

Related Questions