如何在 WooCommerce 中显示购物车项目长度

问题描述

我 WooCommerce 我想显示购物车中商品的长度。

如何在 WooCommerce 中显示购物车商品的长度?

也许有一个简码?

解决方法

要在购物车项目上显示产品长度,请使用 WC_Product get_length() 方法,如下所示:

add_filter( 'woocommerce_get_item_data','display_cart_item_length',20,2 );
function display_cart_item_length( $cart_data,$cart_item ) {
    $product_length = $cart_item['data']->get_length();

    if( ! empty($product_length) ){
        $cart_data[] = array(
            'name' => __( 'Length','woocommerce' ),'value' => wc_format_localized_decimal($product_length) . ' ' . get_option( 'woocommerce_dimension_unit' )
        );
    }
    return $cart_data;
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。


或者如果您想获取商品总长度并将其显示在购物车和结帐中;

// Shortcode to get cart items total length formatted for display
add_shortcode( 'items_total_length','wc_get_cart_items_total_length' );
function wc_get_cart_items_total_length(){
    $total_length = 0; // Initializing variable

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        $product_length = $cart_item['data']->get_length(); // Get producct length

        if( ! empty($product_length) ){
            $total_length += $product_length * $cart_item['quantity']; // Sum item length x quantity
        }
    }
    return wc_format_localized_decimal($total_length) . ' ' . get_option( 'woocommerce_dimension_unit' );
}

// Display total length in cart and checkout
add_action( 'woocommerce_cart_totals_before_order_total','display_cart_total_length' );
add_action( 'woocommerce_review_order_before_order_total','display_cart_total_length' );
function display_cart_total_length() {
    echo '<tr class="length-total">
        <th>' . esc_html__( 'Length','woocommerce' ) . '</th>
        <td>' . do_shortcode("[items_total_length]") . '</td>
    </tr>';
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效