简体   繁体   中英

Get product variation's SKU

I need to e-mail different information to my customers depending on SKU of a products they purchased. The problem is that my products have variations, and each variation has it's own SKU.

I know how to loop through client's order items and get a products SKU...

// Loop through order items
foreach ( $order->get_items() as $item_id => $item ) {
  // Get product ID
  $product_id = $item->get_product_id(); 

  // Get an instance of Product object
  $item->get_product(); 

  // Get SKU
  $sku = $product->get_sku();

  echo $sku;
}

But this code shows SKU of the "original" product, not it's variation:(

This should get what you need:

foreach ( $order->get_items() as $item_id => $item ) {
  // Get product ID
  $product_id = $item->get_product_id(); 

  $args = array(
    'post_type'     => 'product_variation',
    'post_status'   => array( 'private', 'publish' ),
    'numberposts'   => -1,
    'orderby'       => 'menu_order',
    'order'         => 'asc',
    'post_parent'   => $product_id
    );

    $variations = get_posts( $args );

    foreach ( $variations as $variation ) {

       // get variation ID
       $variation_ID = $variation->ID;

       // get variations meta
       $product_variation = new WC_Product_Variation( $variation_ID );

       // get variation featured image
       $variation_sku = $product_variation->get_sku();

    }
}

OK, that was all about my inattentiveness... The code worked fine but the test product's variation had no individual SKU, that's why always got the parent's SKU.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM