douleijiang8111 2015-02-22 20:38
浏览 68
已采纳

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

I'm building a custom function for Woocommerce where I need to get product SKU and if 'variation' product get variation specific SKU.

What I currently have is the following:

// 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();

It works good except when it comes to variations, I Have spent much time trying to figure this out and to find a good answer without any succes.

I come to understand that I should use something like this:

$available_variations = $product->get_available_variations();

The crazy thing is that I did have this working but I didn't made a Git commit, thus I'm not able to revert the correct code. All the examples I found pretty much exist of a lot of code, but I'm sure this can be done using a much simpler and better performing method.

  • 写回答

3条回答 默认 最新

  • douhuan3420 2015-02-22 21:42
    关注

    Talk about tunnel vision..

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

    Solution was switching 'product_id' for my already in place 'variation_id'

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

    Voila, problem solved !

    Working example To get the expected output on $sku i did go for this solution

    // 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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题