php – Woocommerce Convert existing order to the cart

Question

How to transfer an existing and modified order with all its details and its items to the cart.

I want to set the prices directly equal to the modified order as well as the totals without referring to a discount.

I used this code but something is still missing

                foreach ( $order->get_items() as $item ) {
                    $product_id   = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $item->get_product_id() );
                    $quantity     = $item->get_quantity();
                    $variation_id = (int) $item->get_variation_id();
                    $variations   = array();

                    foreach ( $item->get_meta_data() as $meta ) {
                        if ( taxonomy_is_product_attribute( $meta->key ) ) {
                            $term                                    = get_term_by( 'slug', $meta->value, $meta->key );
                            $variations[ 'attribute_' . $meta->key ] = $term ? $term->value : $meta->value;
                        } elseif ( meta_is_product_attribute( $meta->key, $meta->value, $product_id ) ) {
                            $variations[ 'attribute_' . $meta->key ] = $meta->value;
                        }
                    }

                    $cart_item_data = apply_filters( 'woocommerce_order_again_cart_item_data', array(), $item, $order );

                    // Add to cart validation.
                    remove_filter( 'woocommerce_add_to_cart_validation', array( $this, 'cart_validation' ), 10 );

                    if ( ! apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data ) )
                    {
                            continue;
                    }

                    $meta_data = $item->get_meta_data();

                    if ( ! empty( $meta_data ) ) {

                        foreach ( $meta_data as $meta ) {
                            $cart_item_data['meta'][] = $meta->get_data();
                        }
                    }

                    $cart_item_data['meta']['total'] = $item->get_total();
                    $cart_item_data['meta']['subtotal'] = $item->get_subtotal();

                    WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations, $cart_item_data );
                }

                WC()->cart->calculate_totals();

with call the hook add_action('woocommerce_before_calculate_totals')

0
Bahmed Boussada 2 months 2023-02-02T14:34:20-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse