WooCommerce 产品自定义循环由一系列 SKU 过滤

WooCommerce products custom loop filtered by an array of SKUs

我有一个包含几个产品 SKU 的数组,我想显示与这些 SKU 关联的产品。

我找到了自定义 woocommerce 产品循环,但找不到任何关于如何扩展它的文档。


$skus = array(sku1, sku2, sku3);

$args = array(
  'post_type'      => 'product',
  'post_status'    => 'publish',
  'posts_per_page' => -1,
);
$loop = new WP_Query( $args );

if ( $loop->have_posts() ) {
  while ( $loop->have_posts() ) : $loop->the_post();

    wc_get_template_part( 'content', 'product' );

  endwhile;
}
wp_reset_postdata();

你可以试试这个

$skus = array(sku1, sku2, sku3);

$meta_query = array['relation' => 'OR',];

foreach ($skus as $sku) {
    $meta_query[] = array(
        'key' => '_sku',
        'value' => $sku,
        'compare' => '='
    ),
}

$args = array(
    'post_type'      => 'product',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query' => $meta_query
);
$loop = new WP_Query( $args );

if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();

        wc_get_template_part( 'content', 'product' );

    endwhile;
}
wp_reset_postdata();

WP_Query 中,您需要使用 元查询 来获取与一系列 SKU 关联的产品。

代码:

$skus = array('sku1', 'sku2', 'sku3');

$loop = new WP_Query( array(
    'post_type'      => 'product',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query' => array( array(
        'key'     => '_sku',
        'value'   => $skus,
        'compare' => 'IN',
    ) ),
) );

if ( $loop->have_posts() ) :
    while ( $loop->have_posts() ) : $loop->the_post();
        wc_get_template_part( 'content', 'product' );
    endwhile;
endif;
wp_reset_postdata();

已测试并有效。

请参阅 WP_Query and custom field post meta parameters 文档