Archive by Author: Tom

Change product price in WooCommerce programmatically

function change_price_by_type( $product_id, $multiply_price_by, $price_type ) {
	$the_price = get_post_meta( $product_id, '_' . $price_type, true );
	$the_price *= $multiply_price_by;
	update_post_meta( $product_id, '_' . $price_type, $the_price );
}

function change_price_all_types( $product_id, $multiply_price_by ) {
	change_price_by_type( $product_id, $multiply_price_by, 'price' );
	change_price_by_type( $product_id, $multiply_price_by, 'sale_price' );
	change_price_by_type( $product_id, $multiply_price_by, 'regular_price' );
}

/*
 * `change_product_price` is main function you should call to change product's price
 */
function change_product_price( $product_id, $multiply_price_by ) {
	change_price_all_types( $product_id, $multiply_price_by );	
	$product = wc_get_product( $product_id ); // Handling variable products
	if ( $product->is_type( 'variable' ) ) {
		$variations = $product->get_available_variations();
		foreach ( $variations as $variation ) {
			change_price_all_types( $variation['variation_id'], $multiply_price_by );
		}
	}
}