I have a custom field for each simple product that is the volume (in m3) of the item.
I would like to display a message to the user that the volume of their order has not reached 68 m3 (the volume of a 40 foot container). I have reused some code from another function that adds up the values of the volume from the custom field _item_volume
.
How do I display a message when the value has reached 68 m3?
// Loop through cart items and calculate total volume
foreach( WC()->cart->get_cart() as $cart_item ){
$product_volume = (float) get_post_meta( $cart_item['product_id'], '_item_volume', true );
$total_volume += $product_volume * $cart_item['quantity'];
}
Try the following, that will display a custom notice if cart has not reached a total volume of 68m3:
add_action('woocommerce_before_calculate_totals', 'display_custom_notice', 50, 1);
function display_custom_notice( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$total_volume = 0;
// Loop through cart items and calculate total volume
foreach( WC()->cart->get_cart() as $cart_item ){
$product_volume = (float) get_post_meta( $cart_item['product_id'], '_item_volume', true );
$total_volume += $product_volume * $cart_item['quantity'];
}
if( $total_volume < 68 && $total_volume != 0 ){
// Display a custom notice
wc_add_notice( __("Note: Your order total volume has not reached 68 m3", "woocommerce"), 'notice' );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.