Woocommerce Order Again won’t copy custom fields

I’ve managed to code my plugin to add extra custom fields to woocommerce products. This works all the way through from cart to completing an order. Going to my account and viewing past orders, the custom fields are displayed correctly.

However, when I choose to click “order again” on a past order, the new cart doesn’t contain the custom fields and their values.

Read More

Here is what I currently have to attempt this:

// 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;
}

Related posts

Leave a Reply

2 comments

  1. replace

    $cart_item_meta['item_meta'][$key] = $product['item_meta'][$key];
    

    by

    $cart_item_meta[$key] = $product[$key];
    

    Otherwise, why are you removing the validation ?

  2. Here is the code to add all custom field data for order again. Use the given code in your theme’s function.php file and replace the custom field keys of $customfields array with your keys.

    <?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 values of array $customfields with the keys of custom fields that are missing or are not being added automatically.