I am working on an API to automatically import products on Wordpress with Woocommerce. All products are variation products and during the first sync, everything works ok. But after that, if I want to update the products, even if I have a code to avoid it, it creates duplicate variations for that product.

Here is the code:

function insert_product_variations ($post_id, $variations) { foreach ($variations as $index => $variation) { $variation_id = find_matching_product_variation( $post_id, $variation['attributes'] ); if ( $variation_id == 0 ) { $variation_post = array( 'post_title' => 'Variation #'.$index.' of '.count($variations).' for product#'. $post_id, 'post_name' => 'product-'.$post_id.'-variation-'.$index, 'post_status' => 'publish', 'post_parent' => $post_id, 'post_type' => 'product_variation', 'guid' => home_url() . '/?product_variation=product-' . $post_id . '-variation-' . $index ); $variation_post_id = wp_insert_post($variation_post); } else { $variation_post_id = $variation_id; } foreach ($variation['attributes'] as $attribute => $value) { $attribute_term = get_term_by('name', $value, 'pa_'.$attribute); update_post_meta($variation_post_id, 'attribute_pa_'.$attribute, $attribute_term->slug); } update_post_meta($variation_post_id, '_price', $variation['price']); update_post_meta($variation_post_id, '_regular_price', $variation['price']); update_post_meta($variation_post_id, '_sku', $variation['sku']); } } function find_matching_product_variation( $product_id, $attributes ) { $product = wc_get_product( $product_id ); if( class_exists('WC_Data_Store') ) { $data_store = WC_Data_Store::load( 'product' ); return $data_store->find_matching_product_variation( $product, $attributes ); } else { return $product->get_matching_variation( $attributes ); } }

$post_id is the parent_id of the original product and the $variations is an array of objects like this one:

{ "attributes": { "size" : "Small", "color" : "Red" }, "price" : "8.00", "sku" : "TS1000" }