Woocommerce order products by attribute name asc

时间:2017-08-30 20:14:26

标签: php wordpress sorting woocommerce product

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:

elem4 = driver.find_element_by_id("m_sqlRsWebPart_RSWebPartToolbar_ctl00_RptControls_RSActionMenu_ctl01_t")
elem4.click()
actions = ActionChains(driver)
actions.move_to_element(elem4)
actions.perform()
elem4.send_keys(Keys.DOWN)
elem4.send_keys(Keys.DOWN)
elem4.send_keys(Keys.RIGHT)
elem4.send_keys(Keys.DOWN)
elem4.send_keys(Keys.DOWN)
elem4.send_keys(Keys.DOWN)
elem4.click()

1 个答案:

答案 0 :(得分:1)

- 已更新 -

您需要为您的产品属性添加tax_query及其中的相关字词(slugs):

// 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);

此代码经过测试并有效。