Search code examples
phpwordpresswoocommercevolume

Display total cart shipping volume value in Woocommerce


I use woocommerce for wholesale customers who order containers of furniture - normally 40 foot containers with a volume of 68 cubic meters.

Is there a way I can show somewhere on the website - maybe in the header area a box with showing the total m3 of products in their basket? I need to show the client when they reach 68m3 so they know they have filled a container.

And is there a way to flash up a message if a client tries to submit an order less than 68m3 indicating to them that they still have room left in their container?


Solution

  • You can try something like this:

    <?php
        global $woocommerce;
        $items = $woocommerce->cart->get_cart();
        $cart_prods_m3 = array();
    
            //LOOP ALL THE PRODUCTS IN THE CART
            foreach($items as $item => $values) { 
                $_product =  wc_get_product( $values['data']->get_id());
                //GET GET PRODUCT M3 
                $prod_m3 = $_product->get_length() * 
                           $_product->get_width() * 
                           $_product->get_height();
                //MULTIPLY BY THE CART ITEM QUANTITY
                //DIVIDE BY 1000000 (ONE MILLION) IF ENTERING THE SIZE IN CENTIMETERS
                $prod_m3 = ($prod_m3 * $values['quantity']) / 1000000;
                //PUSH RESULT TO ARRAY
                array_push($cart_prods_m3, $prod_m3);
            } 
    
        echo "Total of M3 in the cart: " . array_sum($cart_prods_m3);
    ?>
    

    See WC() docs: https://docs.woocommerce.com/document/class-reference/