按 WooCommerce WC_Product_Query 中的产品属性术语过滤

时间:2020-12-20 15:24:12

标签: php wordpress woocommerce product taxonomy-terms

我正在尝试使用 WC_Product_Query 为产品创建循环。 现在我想按产品属性过滤它们。
使用 WP Query 可以通过 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 Query 中执行此操作的方法:

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

1 个答案:

答案 0 :(得分:2)

就像在 WP_Query 中一样,您可以在 tax_query 中使用 WC_Product_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 开始测试并有效。