Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce products custom loop filtered by an array of SKUs

I have an array which has a couple of product SKU's in it I want to dispay the products that are connected to the SKU's.

I found the custom woocommerce product loop, but can't find any documentation on how to extend this.


$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();
like image 500
CrisC Avatar asked Oct 20 '25 08:10

CrisC


1 Answers

In a WP_Query, you will need to use a meta query to get products that are connected to an array of SKUs.

The code:

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

Tested and works.

See WP_Query and custom field post meta parameters documentation

like image 63
LoicTheAztec Avatar answered Oct 21 '25 21:10

LoicTheAztec