Search code examples
phpwordpresswoocommercehook-woocommerce

How to add/update custom cart item data in the cart page


I want to add a comment to individual products in the cart page. I am new to woocommerce wordpress plugin so I have no idea how to do.

I have done some research. In that tutorial, I found that I can use woocommerce_add_cart_item_data hook this way:

add_filter( 'woocommerce_add_cart_item_data', 'add_comment', 10, 3 );

function add_comment( $cart_item_data, $product_id, $variation_id ) {

    $cart_item_data['comment'] = 'This is comment';

    return $cart_item_data;

}

but this does not work in my case.

I attach the Cart page image so you can understand.

enter image description here

I hope you guys understand what I want?

Thank you.


Solution

  • Below code will add a custom text to an item in cart:

    You need to create a custom field "comment" for the product to use it here.

     add_filter( 'woocommerce_add_cart_item_data', 'add_comment', 10, 3 );
    
    function add_comment( $cart_item_data, $product_id, $variation_id ) {
    
        $cart_item_data['comment'] = 'This is comment';
    
        return $cart_item_data;
    
    }
    

    Add a Custom text/comment before Cart table in Cart Page:

    add_action( 'woocommerce_before_cart_table', 'add_comment' );
    
    function add_comment() 
    {
        echo '<div class="woocommerce-info">This is comment</div>';
    }
    

    Add a Custom text/comment after Cart table in Cart Page:

    add_action( 'woocommerce_after_cart_table', 'add_comment' );
    
    function add_comment() {
        echo '<div class="woocommerce-info">This is comment</div>';
    }
    

    HOW TO ADD AN INPUT FIELD TO WOOCOMMERCE CART ITEMS & Let users update input fields in the cart

    https://pluginrepublic.com/how-to-add-an-input-field-to-woocommerce-cart-items/

    Refer this link for a working solution to similar request: https://stackoverflow.com/a/21818028/12291365

    If you are okay with using the plugin, then this plugin will do the trick: https://wordpress.org/plugins/wc-fields-factory/