按WooCommerce WC_product_Query中的产品属性术语进行筛选



我正在尝试使用WC_Product_Query为产品创建一个循环。现在我想通过产品属性来过滤它们
使用WP查询可以执行此操作,使用tax_Query。但是使用WC_Product_Query是不起作用的
(我不想要WP_Query,因为对于产品,最好使用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;

以下是如何在WP查询中做到这一点:

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

就像在WP_Query中一样,您可以在WC_Product_Query中使用tax_query,如:

$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;

自WooCommerce版本3开始测试并运行。

最新更新