Display total cart shipping volume value in Woocommerce

前端 未结 2 1672
遥遥无期
遥遥无期 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: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';
    

提交回复
热议问题