简体   繁体   English

获取产品变体的 SKU

[英]Get product variation's SKU

I need to e-mail different information to my customers depending on SKU of a products they purchased.我需要根据客户购买的产品的 SKU 通过电子邮件向他们发送不同的信息。 The problem is that my products have variations, and each variation has it's own SKU.问题是我的产品有变体,每个变体都有自己的 SKU。

I know how to loop through client's order items and get a products SKU...我知道如何遍历客户的订单项目并获取产品 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:(但此代码显示的是“原始”产品的 SKU,而不是变体:(

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.好吧,这完全是因为我的注意力不集中......代码运行良好,但测试产品的变体没有单独的 SKU,这就是为什么总是得到父母的 SKU。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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