WoocommerceWordpress

Add bult sale price in all product variations at once

function bulk_add_sales_price( $discount_percentage = 20 ) {
$products = get_posts( [
'post_status' => 'publish',
'post_type' => 'product',
'posts_per_page' => - 1,
] );
$new_factor = 0;
if ( $discount_percentage > 0 && $discount_percentage < 100 ) {
$new_factor = 1 - ( $discount_percentage / 100 );
}
foreach ( $products as $_product ) {
/** @var WC_Product_Variable $product */
$product = wc_get_product( $_product->ID );

$sales_price = '';
if ( $new_factor > 0 ) {
$sales_price = $product->get_price() * $new_factor;
}
$variations = $product->get_children();
if ( ! empty( $variations ) ) {
foreach ( $variations as $variation_id ) {
$pv = new WC_Product_Variation( $variation_id );
$pv->set_sale_price( $sales_price );
$pv->save();
}
}
}
}


If you want to add -20% sales to all products run bulk_add_sales_price( 20 );

if you want to remove the sale price run bulk_add_sales_price( -1 );