skip to Main Content

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

2

Answers


  1. You could try to do this

    $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();
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search