I need to calculate the volume of single order, and store the totale result in the DB to then retrieve it trough the Rest Api and access this parameter there.
i tried to write it down something, but in the checkout i get Internal server error.
This is what I am trying to do (in my imagination):
// 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 = $item['data'];
$qty = $item['quantity'];
// Get product dimensions
$length = $product->get_length();
$width = $product->get_width();
$height = $product->get_height();
// Calculations a item level
$total_volume += $length * $width * $height * $qty;
}
update_post_meta( $order_id, '_item_volume', $total_volume );
}
Thanks for you precious help be patient with me. Thank you again
2
Answers
This should suffice, to store the total volume in the
wp_postmeta
table.$product = $item['data'];
is not correct, causing you to get the following error further in the codeUncaught Error: Call to a member function get_length() on null
. Use$product = $item->get_product();
insteadYou can first save each order item volume as custom order item meta data, with the following:
Then you save the order total volume as order meta data as follows:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.