
An easy two step guide on how to overwrite prices in your Woocommerce shop programatically.
Step 1 – prerequisites
In case you have access to your themes functions.php file, create a backup of it as the first step. Please never use the theme editor in your WordPress dashboard, it will give you a lot of headaches.
If you don’t have access to the functions.php file, download a plugin like the My Custom Functions which gives you the ability to add custom PHP code to your website. For the beginners I recommend this option.
Step 2 – the code
To overwrite the prices in Woocommerce you have two entry points:
- overwrite the prices displayed in your shop globally
- overwrite the price before adding the product to the cart (the price is changed only in your cart)
The rest of the checkout process is handled by the Woocommerce engine.
As an example let’s say you would like to raise the price of every product in your shop by 20%:
/**
* Display the custom price in the shop
*/
function fdev_return_custom_price($price, $product) {
// important lines to handle product discounts!
if($product->is_on_sale()){
return $product->get_sale_price();
}
// change the price display
$price = number_format($price * 1.2, 2);
return $price;
}
add_filter('woocommerce_product_get_price', 'fdev_return_custom_price', 10, 2);
And the same 20% price change, but this time you would like to apply the price change in the cart only and leave the prices in your shop intact:
function fdev_custom_price_to_cart_item( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$product_id = $value['data']->get_id();
$product = wc_get_product($product_id);
// important lines to handle product discounts!
if($product->is_on_sale()){
continue;
}
$new_price = number_format($product->get_price() * 1.2, 2);
$value['data']->set_price($new_price);
$value['new_price'] = $new_price;
}
}
add_action( 'woocommerce_before_calculate_totals', 'fdev_custom_price_to_cart_item' );
In case you encounter any errors, just delete the code from your functions.php file (alternatively replace functions.php with your backup file), or remove the code from the Custom Functions plugin. Happy coding!