I have added a custom variable in the product detail page and I can pass the custom variable value into add to cart function.

public function add_to_cart( $product_id, $quantity = 1, $mmCentre, $variation_id = '', $variation = '', $cart_item_data = array()  ) {
.........
.........
}

So variable $mmCentre is the custom variable.Now I have done this

$this->cart_contents[$cart_item_key] = apply_filters( 'woocommerce_add_cart_item', array_merge( $cart_item_data, array(
                    'product_id'    => $product_id,
                    'variation_id'  => $variation_id,
                    'variation'     => $variation,
                    'quantity'      => $quantity,
                    'data'          => $product_data,
                    'mmCentre'      => $mmCentre
                ) ), $cart_item_key );

The problem is I can’t get that value in cart page.I did a dump of cart_contents but I can’t see the value passed in the array.

Can you please suggest me what is the wrong I am doing?

1 Answer
1

I had to do something similar a while ago, this is what was working for me:

In the example, the custom input name is “test_field” inside the add to cart form, and this way when you dump the cart_contents, you can see the value somewhere at the end

//Store the custom field
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_custom_data_vase', 10, 2 );
function add_cart_item_custom_data_vase( $cart_item_meta, $product_id ) {
  global $woocommerce;
  $cart_item_meta['test_field'] = $_POST['test_field'];
  return $cart_item_meta; 
}

//Get it from the session and add it to the cart variable
function get_cart_items_from_session( $item, $values, $key ) {
    if ( array_key_exists( 'test_field', $values ) )
        $item[ 'mmCentre' ] = $values['test_field'];
    return $item;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'get_cart_items_from_session', 1, 3 );

Leave a Reply

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