Home > OS >  How to Copy a Woocommerce Product's Variations From One Product to Another
How to Copy a Woocommerce Product's Variations From One Product to Another

Time:11-05

I am trying to copy a products variations using PHP from one existing product to another. This way I can copy the variations without duplicating the exact product and having to re input the other non variation customization for that product. I don't know why there isn't a simple plugin for this.

Here is what I have so far, I just don't know how to copy into the new product given both products id's.

if (isset($_POST['submit'])) {
        
        if ($_POST['product_type'] == 'panoramic') {
        $product = wc_get_product( 54721 );

        }
        if ($_POST['product_type'] == 'wide-panoramic') {

                            $product = wc_get_product( 54730 );

        }
        $variations = $product->get_available_variations();
        $new_product = wc_get_product($_POST['product_id_to_fill']);
        $new_product->set_available_variations($variations);
}

(set_available_variations is not actually a function) which is why I've hit a wall.

CodePudding user response:

There isn't a straightforward function like set_available_variations to transfer the variation, have to write a custom code for it, here is the code that I used in one of my own wordpress project, you can modify as per your requirement

if (isset($_POST['submit'])) {
    
    $source_product_id = 54721; 
    $target_product_id = $_POST['product_id_to_fill']; // The ID of the product you want to copy variations to

    $source_product = wc_get_product($source_product_id);

    // Check if the source product has variations
    if ($source_product->is_type('variable')) {
        // Get the variations of the source product
        $variations = $source_product->get_children();

        foreach ($variations as $variation_id) {
            $variation = wc_get_product($variation_id);

            // Create a new variation for the target product
            $new_variation = new WC_Product_Variation();
            $new_variation->set_parent_id($target_product_id);

            // Set attributes and other settings from the source variation
            $new_variation->set_attributes($variation->get_attributes());
            $new_variation->set_regular_price($variation->get_regular_price());
            $new_variation->set_sale_price($variation->get_sale_price());
            $new_variation->set_stock_quantity($variation->get_stock_quantity());
            $new_variation->set_weight($variation->get_weight());

            // Save the new variation
            $new_variation->save();
        }
    }
}
  • Related