php - How to change Woocommerce price?
The prices of products on my site are collected through a robot. All prices are in Turkish lira. I want the price of all products to be converted into dollars. I used this code snippet.
function regular_price_func( $price, $product )
{
//your logic for calculating the new price here
$price = $product->get_regular_price()*1.3;
//Return the new price (this is the price that will be used everywhere in the store)
return $price;
}
add_filter('woocommerce_product_get_price', 'regular_price_func', 99, 2);
Answer
Solution:
Try this, You can change the sale price and regular price and update the condition accordingly.
//Change/Update Regular price
add_filter( 'woocommerce_product_get_regular_price', 'regular_price_func', 10, 2 );
add_filter( 'woocommerce_product_get_price', 'regular_price_func', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'regular_price_func', 10, 2 );
function regular_price_func( $regular_price, $product ) {
$rate = 1.3;
if( empty($regular_price) || $regular_price == 0 ){
return $product->get_price() * $rate;
} else{
return $regular_price * $rate;
}
}
// You can also Change/Update Sale price
add_filter( 'woocommerce_product_get_sale_price', 'woo_sale_price_price_func', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'woo_sale_price_price_func', 10, 2 );
function woo_sale_price_price_func( $sale_price, $product ) {
$rate = 1.3;
if( empty($sale_price) || $sale_price == 0 )
return $product->get_regular_price() * $rate;
else
return $sale_price * $rate;
};
Answer
Solution:
If you're looking to alter either the regular price OR the sale price. You have to specify which ones you want to use.
Also, the hook woocommerce_product_get_price
is deprecated as of 3.0, the replacement for this is woocommerce_get_price
- and finally, this filter returns price as a string, so to multiply a value, you need the floatval
of that string.
function regular_price_func($price, $product) {
if ($product->is_on_sale()){
$price = floatval($product->get_sale_price()) * 1.3;
} else {
$price = floatval( $product->get_regular_price() ) * 1.3;
}
//Return the new price (this is the price that will be used everywhere in the store)
return $price;
}
add_filter( 'woocommerce_get_price', 'regular_price_func', 99, 2 );
Source