【问题标题】:Store the total volume of the items from a WooCommerce order in the DB将 WooCommerce 订单中的商品总量存储在数据库中
【发布时间】:2021-01-28 09:48:32
【问题描述】:

我不太确定自己在做什么,但简而言之,我想计算订单中所有商品的数量并将其存储在数据库中。我正在使用 woocommerce Rest API,当我检索订单时,我没有购买商品的 3 个度量值,所以我想按照我已经将总重量存储为数据库中的元数据然后通过 API 检索。

我正在使用以下内容:

// Store volume in the database
add_action('woocommerce_checkout_update_order_meta', 'woo_add_cart_volume');

function woo_add_cart_volume( $order_id ) {
    global $woocommerce;

     foreach( $order->get_items() as $item ){
        $product_volume = (float) get_post_meta( $item->get_product_id(), '_item_volume', true );
        $total_volume  += $product_volume * $item->get_quantity();
    }
    
    update_post_meta( $order_id, '_item_volume', $total_volume );
}

但它会破坏订单流程并引发内部服务器错误。

你能帮我调整一下吗?

【问题讨论】:

  • foreach( $order->, $order 未定义

标签: php wordpress object woocommerce orders


【解决方案1】:

您的代码中缺少一些部分:

  • 在使用get_items()方法之前需要定义$order
  • 之前还需要初始化$total_volume

改用:

// Store volume in the database
add_action('woocommerce_checkout_update_order_meta', 'woo_add_cart_volume');

function woo_add_cart_volume( $order_id ) {
    $order        = wc_get_order( $order_id ); // <== Was missing
    $total_volume = 0; // Initializing variable

    foreach( $order->get_items() as $item ){
        $product_volume = (float) get_post_meta( $item->get_product_id(), '_item_volume', true );
        $total_volume  += $product_volume * $item->get_quantity();
    }
    
    update_post_meta( $order_id, '_item_volume', $total_volume );
}

现在应该可以更好地工作了。

【讨论】:

  • 谢谢。它有效,但我们缺少一些东西。我下了订单试一试。我通过其余的 Api 检索了订单,我看到了这个:``` { "id": 311972, "key": "_cart_weight", "value": "26" }, { "id": 311973, "key": "_item_volume", "value": "0" }, ``` 体积为 0.. 我检查了对象并具有 3 个维度。为什么是0?我缺少什么?谢谢
  • 对不起,我不知道该怎么做.. 现在我接受了。我知道你真的很擅长它,因为我看到了你在这个问题上给出的其他答案:我认为我们首先需要计算体积,然后将其作为参数存储在 _item_volume' 元数据中。你能帮我解决这个问题吗?
  • @LoicTheAztec 你的意思是在主要部分打开一个新问题?
猜你喜欢
  • 2019-02-23
  • 2021-02-07
  • 2021-07-24
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 2019-05-10
相关资源
最近更新 更多