I'm using Woocommerce and I'm trying to display the product weight for each product on cart page.

I have used this:

add_action('woocommerce_cart_collaterals', 'myprefix_cart_extra_info');
function myprefix_cart_extra_info() {
    global $woocommerce;
    echo '<div class="cart-extra-info">';
    echo '<p class="total-weight">' . __('Total Weight:', 'woocommerce');
    echo ' ' . $woocommerce->cart->cart_contents_weight . ' ' . get_option('woocommerce_weight_unit');
    echo '</p>';
    echo '</div>';
}

It display the total cart weight. I would like to also show the weight of each item in the cart as well.

How to display the product weight of each item on cart page?

Thanks.

1 Answers

1
LoicTheAztec On

You can use the custom function hooked in woocommerce_get_item_data filter hook below, to display the product weight of each cart items:

add_filter( 'woocommerce_get_item_data', 'displaying_cart_items_weight', 11, 2 );
function displaying_cart_items_weight( $item_data, $cart_item ) {

    $item_id = $cart_item['variation_id'];
    if($item_id == 0) $item_id = $cart_item['product_id'];
    $product_qty = $cart_item['quantity'];
    $product = wc_get_product($item_id);
    $weight_value = $product->get_weight();
    $weight_display = $weight_value . ' ' . get_option('woocommerce_weight_unit');

    $item_data[] = array(
        'key'       => __('Weight', 'woocommerce'),
        'value'     => $weight_value,
        'display'   => $weight_display
    );

    return $item_data;
}

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.


If you want to get the total line cart item weight (product weight x product quantity) you will need replace this line:

$weight_value = $product->get_weight();

…by this one:

$weight_value = $product->get_weight() * $product_qty;

…in the function code.


Reference: Class WC_Product::get_weight()