在 Woocommerce 中显示总购物车运输量值

Jam*_*ald 2 php wordpress volume shipping woocommerce

我为订购家具集装箱的批发客户使用 woocommerce - 通常为 40 英尺集装箱,容积为 68 立方米。

有没有办法可以在网站上的某个地方显示 - 也许在标题区域有一个框,显示他们篮子中产品的总立方米?当他们达到 68 立方米时,我需要向客户展示,以便他们知道他们已经装满了一个容器。

如果客户尝试提交小于 68m3 的订单,是否有办法闪现一条消息,向他们表明他们的容器中还有剩余空间?

任何帮助表示赞赏。

Loi*_*tec 6

这是一个函数,它将自动获取 Woocommerce 中设置的尺寸单位,并计算总购物车体积:

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;
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。测试和工作。

示例用法输出:

echo __('Cart volume') . ': ' . get_cart_volume() . ' m3';
Run Code Online (Sandbox Code Playgroud)