我正在为 Woocommerce 构建一个自定义函数,我需要在其中获取产品 SKU,如果“变体”产品获得变体特定的 SKU。
我目前拥有的是:
// Query order data
$order = new WC_Order($order_id);
$items = $order->get_items();
// Output the loop
foreach ($order->get_items() as $item) {
// Getting some information
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_qty = $item['qty'];
$product_variation_id = $item['variation_id'];
$product = new WC_Product($item['product_id']);
// SKU
$SKU = $product->get_sku();
它工作得很好,除非涉及到变化,我花了很多时间试图弄清楚这个问题并找到一个好的答案但没有成功。
我开始明白我应该使用这样的东西:
$available_variations = $product->get_available_variations();
疯狂的是我确实有这个工作,但我没有提交 Git,因此我无法恢复正确的代码。我发现的所有示例几乎都包含大量代码,但我确信这可以使用更简单、性能更好的方法来完成。
最佳答案
谈论隧道视野..
$product_variation_id = $item['variation_id'];
$product = new WC_Product($item['product_id']);
解决方案是将“product_id”切换为我已经存在的“variation_id”
$product = new WC_Product($item['variation_id']);
瞧,问题解决了!
工作示例
为了在 $sku
上获得预期的输出,我确实选择了这个解决方案
// Get order data
$order = new WC_Order($order_id);
$items = $order->get_items();
// Loop through ordered items
foreach ($items as $item) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_qty = $item['qty'];
$product_variation_id = $item['variation_id'];
// Check if product has variation.
if ($product_variation_id) {
$product = new WC_Product($item['variation_id']);
} else {
$product = new WC_Product($item['product_id']);
}
// Get SKU
$sku = $product->get_sku();
}
关于php - WooCommerce get_sku();产品变化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28662963/