Display the total weight in the cart and order page of woocommerce

We often encounter issues with WooCommerce shipping rules, particularly if the shipping rule does not include a large enough weight rule.

For example we had configured rules up to 10KG, except a customer wanted to buy for more than 10KG.

This piece of code will allow you to display in the basket and order validation page the total weight of the products in the basket.
So if it is a weight problem regarding the shipping rule you will be able to resolve the problem in two seconds!

Simply add this snippet to your child theme’s functions.php :

				
					// Afficher le poids total des articles dans le panier WooCommerce en kilogrammes
add_action( 'woocommerce_cart_totals_before_order_total', 'display_cart_total_weight_kg' );
add_action( 'woocommerce_review_order_before_order_total', 'display_cart_total_weight_kg' );

function display_cart_total_weight_kg() {
    // Calculer le poids total en kilogrammes
    $total_weight = 0;

    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $product = $cart_item['data'];
        $quantity = $cart_item['quantity'];
        $weight = $product->get_weight();
        
        if ( $weight ) {
            $total_weight += ( $weight * $quantity );
        }
    }

    // Convertir en kilogrammes si nécessaire
    $weight_unit = get_option( 'woocommerce_weight_unit' );
    if ( $weight_unit !== 'kg' ) {
        $total_weight = wc_get_weight( $total_weight, 'kg' );
    }

    if ( $total_weight > 0 ) {
        echo '<tr class="cart-total-weight"><th>' . __( 'Total KG', 'woocommerce' ) . '</th><td data-title="' . __( 'Total KG', 'woocommerce' ) . '">' . number_format( $total_weight, 2 ) . ' kg</td></tr>';
    }
}

				
			
Want to leave a comment ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to see more code snippets?

Back to Top for Elementor

“Back to Top” button with progressive fill based on scroll. Automatically uses Elementor's main color.

WooCommerce Gallery Hover for Elementor Loop

Displays the first image in the gallery when hovering over the featured image in Elementor loops.

Free shipping method with WooCommerce coupon

Offer free shipping… but only for the shipping method you choose.

WooCommerce Product Buyers List

Added a tab in WooCommerce to display buyers of a specific product with date filter.

Additional Emails per Products for WooCommerce

Adds a custom tab in WooCommerce products to write an email specific to each product. This will be sent in a dedicated email.

Create a custom gallery with Elementor

With this code we gonna add a custom gallery to an elementor page
Let's talk ?

A question about WordPress?
A web project to be outsourced to a freelancer?
I am your man!