79186157

Date: 2024-11-13 18:15:05
Score: 2.5
Natty:
Report link

After Moshe Gross's answer, I added a cleanup routine to the perform_wvc_copy function, removing any existing product variations before the copy.

The fixed function:

function perform_wcv_copy() {
    global $options;
    $source_product_id = get_option('source_product_id');
    $target_product_id = get_option('target_product_id');

    $source_product = wc_get_product($source_product_id);
    $target_product = wc_get_product($target_product_id);

    // Check if source and target products have variations
    if ($source_product->is_type('variable') && $target_product->is_type('variable')) {

        // Get the variations of the target product
        $t_variations = $target_product->get_children();

        // Delete existing product variations
        foreach ($t_variations as $t_variation_id) {
            $t_variation = wc_get_product($t_variation_id);
            $t_variation->delete( true );
        }
    }        

    // Check if the source product has variations
    if ($source_product->is_type('variable')) {
        if (!$target_product->is_type('variable')) {
            /* Update target parent */
            $target_product = wc_get_product($target_product_id);
            $target_product->set_attributes($source_product->get_attributes());
            $target_product->save();
            wp_set_object_terms( $target_product_id, 'variable', 'product_type' );
        }
    
        // 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_weight($variation->get_weight());
            $new_variation->set_length($variation->get_length());
            $new_variation->set_height($variation->get_height());
            $new_variation->set_width($variation->get_width());
            
            // Save the new variation
            $new_variation->save();
        }
    }
    update_option( 'wcvc_status', 'done' );
}

If there's anything else, please provide a comment or answer.

Reasons:
  • RegEx Blacklisted phrase (2.5): please provide
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Wayne Schulz