猿问

如何确定使用该产品购买了该产品的哪个 WooCommerce 变体

在 woocommerce_payment_complete 挂钩期间,我收到订单,然后使用 get_items() 从中提取产品。从这里开始,当我遍历项目并使用 get_sku() 获取 SKU 时,返回主要产品的 SKU 而不是所购买变体的 SKU。

我一整天都在谷歌上搜索这个问题,我收到了很多帖子告诉我一旦你有了变体 ID,如何用变体做各种各样的事情......但对于我的生活,我无法想象了解如何获取变体 ID!

简单地说:我的网站上有一个产品(一顶帽子),该产品有 3 个变体(棒球、三角帽、stetson),每个变体都有一个自定义 SKU,Item_hat_stetson 设置为默认值。我只想知道“这个人选择购买三顶帽子中的哪一顶?” 然而我能确定的是:

  1. 是的,他买了一顶帽子:SKU Item_hat

  2. 帽子有棒球帽、三角帽和斯泰森帽

我如何确定该人选择了哪种变体?

很简单吧?......但对于我的生活,我就是无法弄清楚。:( 请帮忙...

谢谢


UYOU
浏览 181回答 2
2回答

慕容708150

在您的 woocommerce 付款完整挂钩中尝试此操作。$order = wc_get_order( $order_id ); // Loop though order "line items"foreach( $order->get_items() as $item_id => $item_product ){    $product_id = $item_product->get_product_id(); //Get the product ID    $quantity = $item_product->get_quantity(); //Get the product QTY    $product_name = $item_product->get_name(); //Get the product NAME     // Get an instance of the WC_Product object (can be a product variation  too)    $product = $item_product->get_product();     // Get the product description (works for product variation)    $description = $product->get_description();    // Only for product variation    if($product->is_type('variation')){         // Get the variation attributes        $variation_attributes = $product->get_variation_attributes();        // Loop through each selected attributes        foreach($variation_attributes as $attribute_taxonomy => $term_slug){            $taxonomy = str_replace('attribute_', '', $attribute_taxonomy );            // The name of the attribute            $attribute_name = get_taxonomy( $taxonomy )->labels->singular_name;            // The term name (or value) for this attribute            $attribute_value = get_term_by( 'slug', $term_slug, $taxonomy )->name;        }    }}
随时随地看视频慕课网APP
我要回答