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.

2 Views

Tags

Language

Did it work?

Save Snippet

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.