Woocommerce order again won't copy custom fields
I have managed to code my plugin to add additional custom fields to woocommerce products. It runs from cart to order completion. Going to my account and viewing past orders, the custom fields are displayed correctly.
However, when I select "order again" in the previous order, the new cart does not contain the custom fields and their values.
Here's what I need to do now:
// order again
add_filter( 'woocommerce_order_again_cart_item_data', 'woocommerce_order_again_cart_item_data', 10, 3 );
function woocommerce_order_again_cart_item_data($cart_item_meta, $product, $order){
global $woocommerce;
// Disable validation
remove_filter( 'woocommerce_add_to_cart_validation', array( $this, 'validate_add_cart_item' ), 10, 3 );
if ( ! array_key_exists( 'item_meta', $cart_item_meta ) || ! is_array( $cart_item_meta['item_meta'] ) )
$cart_item_meta['item_meta'] = array();
foreach ( array( 'jhpc_toppings', 'jhpc_sauce', 'jhpc_toppings_half', 'jhpc_sauce_half', 'jhpc_garnish' ) as $key )
$cart_item_meta['item_meta'][$key] = $product['item_meta'][$key];
return $cart_item_meta;
}
+3
source to share
2 answers
Here is the code to add all custom field data for the order again. Use this code in your theme's theme.php file and replace the custom keys of the $ customfields array with yours.
<?php
add_filter( 'woocommerce_order_again_cart_item_data', 'wpso2523951_order_again_cart_item_data', 10, 3 );
function wpso2523951_order_again_cart_item_data($cart_item_meta, $product, $order){
//Create an array of all the missing custom field keys that needs to be added in cart item.
$customfields = [
'customfield_key1',
'customfield_key2',
'customfield_key3',
'customfield_key4',
];
global $woocommerce;
remove_all_filters( 'woocommerce_add_to_cart_validation' );
if ( ! array_key_exists( 'item_meta', $cart_item_meta ) || ! is_array( $cart_item_meta['item_meta'] ) )
foreach ( $customfields as $key ){
if(!empty($product[$key])){
$cart_item_meta[$key] = $product[$key];
}
}
return $cart_item_meta;
}
?>
Replace the $ customfields array values with custom field keys that are missing or not automatically added.
0
source to share