Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juanlistab/634f7c2afe66e22f8b8475a5fb1706ba to your computer and use it in GitHub Desktop.
Save juanlistab/634f7c2afe66e22f8b8475a5fb1706ba to your computer and use it in GitHub Desktop.
Use the price of an existing variation when importing variations without price

Use the price of an existing variation when importing variations without price

Instructions:

function my_before_variable_product_import($product_id) {
    global $wpdb;

    $product = wc_get_product($product_id);
    if ($product && $product->is_type('variable')) {
        $children = $product->get_children();

        // Query to get the first variation with a price
        $price_query = "SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id IN (" . implode(',', $children) . ") AND meta_key = '_price' AND meta_value > '' ORDER BY meta_id ASC LIMIT 1";
        $price = $wpdb->get_var($price_query);

        // Check if a price is found
        if (!empty($price)) {
            // Loop through each child and set the price
            foreach ($children as $child_id) {
                update_post_meta($child_id, '_price', $price);
                update_post_meta($child_id, '_regular_price', $price);
                
                // Update the product object and save it
                $child_product = wc_get_product($child_id);
                if ($child_product) {
                    $child_product->set_price($price);
                    $child_product->set_regular_price($price);
                    $child_product->save();
                }
            }
        }
    }
}

add_action('wp_all_import_before_variable_product_import', 'my_before_variable_product_import', 10, 1);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment