【问题标题】:Filter by product attribute terms in a WooCommerce WC_Product_Query在 WooCommerce WC_Product_Query 中按产品属性术语过滤
【发布时间】:2021-03-30 13:13:32
【问题描述】:

我正在尝试使用 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 );

【问题讨论】:

    标签: php wordpress woocommerce product taxonomy-terms


    【解决方案1】:

    就像在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 开始测试和工作。

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 2011-06-22
      • 2020-08-30
      • 2016-02-20
      相关资源
      最近更新 更多