Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

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

I am not really sure of what I am doing, but in a nutshell I want to calculate the volume of all items from an order and store it in the DB. I am working with the woocommerce Rest API and when I retrieve the order I don't have the 3 measures of the item bought so I thought to do as I have already done with the total weight stored as a meta data in the db and then retrieved trough the API.

I am using the following:

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

But it breaks the process of the order and throws an Internal server Error.

Can you help me to adjust it?

question from:https://stackoverflow.com/questions/65934612/store-the-total-volume-of-the-items-from-a-woocommerce-order-in-the-db

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are some missing parts in your code:

  • The $order need to be defined before using get_items() method on it,
  • Also $total_volume need to be initialized before.

Use instead:

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

Now it should better work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...