WAIT: Error when opening cart page: Undefined variable $cart_item_data

Hello I am new to custom plugin building. I am trying to add a product to the Woocommerce cart with some custom additional data (an ‘emaill’ field). I think the addition to the cart works well since two lines of the same product are shown on the cart page. However, I would like it to be visible on the cart like on the following picture:

Additional info seen on cart page

To add the product to the cart I use the following code:

WC()->cart->add_to_cart( $product_id, $quantity );

And the following filter is added to the woocommerce_add_cart_item_data to make sure the ‘emaill’ value is added to the cart item:

function plugin_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
  error_log("plugin_add_cart_item_data called");
  if( isset( $_POST['emaill'] ) ) {
    $cart_item_data['emaill'] = sanitize_text_field( $_POST['emaill'] );
  }
  return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'plugin_add_cart_item_data', 10, 3 );

To see the extra ‘emaill’ info like in the picture above, I added the following code:

function plugin_republic_get_item_data( $item_data, $cart_item_data ) {
  error_log("plugin_republic_get_item_data called");
  if( isset( $cart_item_data['emaill'] ) ) {
    $item_data[] = array(
    'key' => __( 'Your name', 'plugin-republic' ),
    'value' => wc_clean( $cart_item_data['emaill'] ));
  }
  return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'plugin_republic_get_item_data', 10, 2 );

But the products are just shown as this; no ‘emaill’ value shown here:

cart

When looking at the debug.log file, I can see that the plugin_add_cart_item_data called is logged when adding a new item, but the plugin_republic_get_item_data called is not logged when opening the cart page.

Could someone point me. where to look for this issue? I also don’t know in which database table the ‘emaill’ info should be included.

Thanks!

Hi @BackeIT ,

This is not related to BUG, I just moved this thread to How To.

I am not so sure what your full code looks like. But I wonder how you get the $_POST[‘emaill’] from WC()->cart->add_to_cart( $product_id, $quantity );

Kindly change the error log line inside the isset( $_POST['emaill'] ) to check if it’s called.

It’s a high chance that $_POST['emaill'] not exists so it’s not saved into the cart item data.

function plugin_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
  
  if( isset( $_POST['emaill'] ) ) {
    error_log("plugin_add_cart_item_data called");
    $cart_item_data['emaill'] = sanitize_text_field( $_POST['emaill'] );
  }
  return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'plugin_add_cart_item_data', 10, 3 );

Additionally, you should use sanitize_email if want to ensure it’s an email.

Regards,
Jenn