Display total cart shipping volume value in Woocommerce

前端 未结 2 1686
遥遥无期
遥遥无期 2021-01-15 08:19

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

相关标签:
2条回答
  • 2021-01-15 08:45

    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/

    0 讨论(0)
  • 2021-01-15 08:55

    Here is a function that will get automatically the dimension unit set in Woocommerce and that will do the total cart volume calculation:

    function get_cart_volume(){
        // Initializing variables
        $volume = $rate = 0;
    
        // Get the dimetion unit set in Woocommerce
        $dimension_unit = get_option( 'woocommerce_dimension_unit' );
    
        // Calculate the rate to be applied for volume in m3
        if ( $dimension_unit == 'mm' ) {
            $rate = pow(10, 9);
        } elseif ( $dimension_unit == 'cm' ) {
            $rate = pow(10, 6);
        } elseif ( $dimension_unit == 'm' ) {
            $rate = 1;
        }
    
        if( $rate == 0 ) return false; // Exit
    
        // Loop through cart items
        foreach(WC()->cart->get_cart() as $cart_item) { 
            // Get an instance of the WC_Product object and cart quantity
            $product = $cart_item['data'];
            $qty     = $cart_item['quantity'];
    
            // Get product dimensions  
            $length = $product->get_length();
            $width  = $product->get_width();
            $height = $product->get_height();
    
            // Calculations a item level
            $volume += $length * $width * $height * $qty;
        } 
        return $volume / $rate;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    Example usage output:

    echo __('Cart volume') . ': ' . get_cart_volume() . ' m3';
    
    0 讨论(0)
提交回复
热议问题