Reputation: 421
So currently have enabled in WooCommerce a custom Ajax add to cart via admin that allows me to add custom additional data as follows:
$cart->add_to_cart($product_id , 1, 0, $variation, array('tmcartepo'=>$extra_options_data ) );
And it works nicely.
But the problem is, I need to set 2 (two) arrays of custom additional data on add_to_cart()
.
Any help is much appreciated.
Basically, this site has Product designer and extra custom fields for products, all managed by separate plugins. My task is to create single product reorder in my account. So, I want to add new product to cart and set two different arrays with metadata for that product.
Upvotes: 2
Views: 1409
Reputation: 253919
Assuming $extra_options_data
variable is an array you can embed it in another array, which will allow to add a 2nd $extra_options_data_2
variable array like:
$custom_data = array( 'tmcartepo'=> array(
'option1' => $extra_options_data,
'option2' => $extra_options_data_2,
) );
$cart->add_to_cart( $product_id , 1, 0, array(), $custom_data );
Then on cart items you will access both as follows:
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Access first custom data array
if( isset($cart_item['tmcartepo']['option1']) && ! empty($cart_item['tmcartepo']['option1']) ) {
$extra_options_data = $cart_item['tmcartepo']['option1'];
}
// Access Second custom data array
if( isset($cart_item['tmcartepo']['option1']) && ! empty($cart_item['tmcartepo']['option1']) ) {
$extra_options_data_2 = $cart_item['tmcartepo']['option2'];
}
}
Or you can also use it as follows:
$custom_data = array(
'tmcartepo' => $extra_options_data,
'tmcartepo2' => $extra_options_data_2,
);
Then on cart items you will access both as follows:
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Access first custom data array
if( isset($cart_item['tmcartepo']) && ! empty($cart_item['tmcartepo']) ) {
$extra_options_data = $cart_item['tmcartepo'];
}
// Access Second custom data array
if( isset($cart_item['tmcartepo2']) && ! empty($cart_item['tmcartepo2']) ) {
$extra_options_data_2 = $cart_item['tmcartepo2'];
}
}
Upvotes: 2