Add Custom Field to Cart Item
This snippet demonstrates how to add a custom field to cart items, allowing for additional data to be stored with each item.
PHP
function add_custom_field_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
$custom_field = filter_input( INPUT_POST, 'custom_field' );
if ( ! empty( $custom_field ) ) {
$cart_item_data['custom_field'] = $custom_field;
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_field_to_cart_item', 10, 3 );
function display_custom_field_in_cart( $item_data, $cart_item ) {
if ( isset( $cart_item['custom_field'] ) ) {
$item_data[] = array(
'key' => 'Custom Field',
'value' => wc_clean( $cart_item['custom_field'] ),
'display' => '',
);
}
return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_custom_field_in_cart', 10, 2 );
Snippet Feedback
Did this snippet work for you? Do you have any questions about this snippet? Leave some feedback below.
SHARED BY
2 Views