Reputation: 483
I have code which passes a single custom field to the shopping cart. This is made possible through the $item_data array. How can I expand the array to add another item? For instance the enrolmentId?
The code is below:
function display_enrolment_text_cart( $item_data, $cart_item ) {
if ( empty( $cart_item['enrolmentName'] ) ) {
return $item_data;
}
$item_data[] = array(
'key' => __( 'Enrolment', 'test' ),
'value' => wc_clean( $cart_item['enrolmentName'] ),
'display' => '',
);
// add another item to the $item_data[] array
return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_enrolment_text_cart', 10, 2 );
Upvotes: 2
Views: 1722
Reputation: 253784
The code tha you are using is not passing any item to cart, it's just displaying existing custom cart item data.
To add custom cart item data from additional product fields or something else related, you will use something like (requires some additional fields on single product pages for example):
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 3 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){
if( isset( $_POST['product_field1'] ) ) {
$cart_item_data['custom_data'][1] = sanitize_text_field( $_POST['product_field1'] );
}
if( isset( $_POST['product_field2'] ) ) {
$cart_item_data['custom_data'][2] = sanitize_text_field( $_POST['product_field2'] );
}
return $cart_item_data;
}
Now to display that custom cart item data in cart and checkout pages:
add_filter( 'woocommerce_get_item_data', 'display_enrolment_text_cart', 10, 2 );
function display_enrolment_text_cart( $item_data, $cart_item ) {
if ( isset($cart_item['enrolmentName']) && ! empty($cart_item['enrolmentName']) ) {
$item_data[] = array(
'key' => __( 'Enrolment', 'test' ),
'value' => wc_clean( $cart_item['enrolmentName'] ),
'display' => '',
);
}
// Additional displayed custom cat item data
if ( isset($cart_item['custom_data'][1]) && ! empty($cart_item['custom_data'][1]) ) {
$item_data[] = array(
'key' => __( 'Field 1', 'test' ),
'value' => wc_clean( $cart_item['custom_data'][1] ),
'display' => '',
);
}
if ( isset($cart_item['custom_data'][2]) && ! empty($cart_item['custom_data'][2]) ) {
$item_data[] = array(
'key' => __( 'Field 2', 'test' ),
'value' => wc_clean( $cart_item['custom_data'][2] ),
'display' => '',
);
}
return $item_data;
}
Code goes in function.php file of your active child theme (or active theme). It should works.
Related thread: Store custom data using WC_Cart add_to_cart() method in Woocommerce 3
Related complete thread: Add custom field in products to display in cart, checkout and in orders
Upvotes: 2