WooCommerce get_sku();关于产品的顺序变化

时间:2015-02-22 20:38:06

标签: php wordpress woocommerce

我正在为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提交,因此我无法恢复正确的代码。我发现的所有示例都存在很多代码,但我确信这可以使用更简单,性能更好的方法来完成。

4 个答案:

答案 0 :(得分:24)

谈论隧道视觉......

 $product_variation_id = $item['variation_id'];
 $product = new WC_Product($item['product_id']);

解决方案是为我已经到位的'variation_id'

切换'product_id'
$product = new WC_Product($item['variation_id']);

Voila,问题解决了!

工作示例 为了在$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();
}

答案 1 :(得分:11)

WooCommerce 3.x 上,此行会引发致命错误:

$product = new WC_Product($item['variation_id']);

未捕获的例外'例外情况'消息'无效产品'。

你可以这样做:

$sku = get_post_meta( $item['variation_id'], '_sku', true );

答案 2 :(得分:1)

我发现以下链接非常有用,因为它将SKU添加到订单商品元素中,因此无需额外调用函数。

https://majemedia.com/woocommerce-save-item-sku-to-order-item-meta-for-historical-reference/

答案 3 :(得分:0)

经过Woocommerce 3.8.1的测试


@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) {  }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const currentUser = this.authenticationService.currentUserValue;
        if (currentUser) {
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['login'], { queryParams: { returnUrl: state.url } });
        return false;
    }
}