In my WooCommerce shop customers can only buy one product. They can add this single product multiple times to the cart, but with different custom meta values. Customers are able to edit their products from the cart (WooCommerce default functionality) and change the meta they initially filled in.
In my functions.php
I have the following code:
function add_names_on_tshirt_field() {
global $post;
$name_one_on_tshirt = "";
$name_two_on_tshirt = "";
$name_three_on_tshirt = "";
foreach ( WC()->cart->cart_contents as $key => $value ) {
if( $value["product_id"] == $post->ID && isset( $value["name_one_on_tshirt"] ) ) {
$name_one_on_tshirt = $value["name_one_on_tshirt"];
}
if( $value["product_id"] == $post->ID && isset( $value["name_two_on_tshirt"] ) ) {
$name_two_on_tshirt = $value["name_two_on_tshirt"];
}
if( $value["product_id"] == $post->ID && isset( $value["name_three_on_tshirt"] ) ) {
$name_three_on_tshirt = $value["name_three_on_tshirt"];
}
}
echo '<table class="variations" cellspacing="0">
<tbody>
<tr>
<td class="label"><label for="color">Name 1 on T-Shirt</label></td>
<td class="value">
<input type="text" name="name-one-on-tshirt" value="'. esc_attr( $name_one_on_tshirt ) .'" />
</td>
</tr>
<tr>
<td class="label"><label for="color">Name 2 on T-Shirt</label></td>
<td class="value">
<input type="text" name="name-two-on-tshirt" value="'. esc_attr( $name_two_on_tshirt ) .'" />
</td>
</tr>
<tr>
<td class="label"><label for="color">Name 3 on T-Shirt</label></td>
<td class="value">
<input type="text" name="name-three-on-tshirt" value="'. esc_attr( $name_three_on_tshirt ) .'" />
</td>
</tr>
</tbody>
</table>';
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_names_on_tshirt_field' );
The problem lies in when my customers try to edit a product from the cart. Because all products have the same ID (I only have one product), the meta from the last product added to the cart is loaded into the text fields. I currently retrieve the meta in my foreach
using the product id, but the ID is the same as all other products in my cart. Is there another way to retrieve the meta without using the product_id
/$post->ID
, like the cart_item_key
or using sessions?