I WooCommerce I would like to display the length of the items in the cart.
How to display cart items length in WooCommerce?
Maybe there is a shortcode for that?
I WooCommerce I would like to display the length of the items in the cart.
How to display cart items length in WooCommerce?
Maybe there is a shortcode for that?
To display the product length on cart items, use the WC_Product
get_length()
method as follows:
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;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Or if you want to get total items length and display it in cart and checkout use;
// 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>';
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works