/**
* Sets product price.
*
* @see https://wpcodebook.com/change-product-price-in-woocommerce-programmatically/
*
* @param int|WC_Product $product Product ID or WC_Product object.
* @param string $price Price.
* @param string $regular_or_sale Price type. Possible values: regular, sale. Default: regular.
* @param bool $apply_to_all_variations Whether to set the price for all product variations as well. Default: false.
*
* @return bool
*/
function wpcodebook_set_product_price( $product, $price, $regular_or_sale = 'regular', $apply_to_all_variations = false ) {
if ( is_numeric( $product ) ) {
$product = wc_get_product( $product );
}
if ( ! $product ) {
return false;
}
if ( ! $product->is_type( 'variable' ) ) {
if ( 'sale' === $regular_or_sale ) {
$product->set_sale_price( $price );
} else {
$product->set_regular_price( $price );
}
$product->save();
} else {
if ( ! $apply_to_all_variations ) {
return true;
}
foreach ( $product->get_children() as $variation_id ) {
if ( ! wpcodebook_set_product_price( $variation_id, $price, $regular_or_sale ) ) {
return false;
}
}
}
return true;
}