wordpresswoocommerce

How to show product weight to wc_add_to_cart_message_html?


I am looking for a solution to show product weight in the success message. I use the following lines, but I face an error that mention there is a critical error in your website:

add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_function', 10, 2 ); 

function my_add_to_cart_function( $message, $product_id ) { 

    $message = sprintf('<span style="font-size: 12px;"> %s  has been added by to your basket.</span><br><span style="font-size: 12px;">Weight: %s </span><a href="https://example.com/cart/" class="w-100 add-to-card-pills btn mt-3">View Basket</a>', 
    get_the_title( $product_id ) ,
    get_the_weight( $product_id ) 
    
    ); 
    return $message; 
    
}

Is there any way to get the weight, picture thumbnail and meta_key in $message?


Solution

  • use this code

    add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_function', 10, 2 ); 
    
    function my_add_to_cart_function( $message, $product_id ) {
    
        $product = wc_get_product($product_id);
        
    
        $message = sprintf('<span style="font-size: 12px;"> %s  has been added by to your basket.</span><br><span style="font-size: 12px;">Weight: %s </span><a href="https://example.com/cart/" class="w-100 add-to-card-pills btn mt-3">View Basket</a>', 
        get_the_title( $product_id ) ,
        $product->get_weight()
        
        ); 
        return $message; 
        
    }
    

    there is no such function get_the_weight so you need to get_weight from product object. Tested & works