将 WooCommerce 订单中的商品总量存储在数据库中

Store the total volume of the items from a WooCommerce order in the DB

我不太确定自己在做什么,但简而言之,我想计算订单中所有商品的数量并将其存储在数据库中。我正在使用 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 );
}

但是它中断了订单的处理并抛出内部服务器错误。

你能帮我调整一下吗?

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

  • 在使用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 );
}

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