I am trying to programmatically change the pricing of my WooCommerce products from $4.49 to $5. It works nice.
While the product price is nicely visibly everywhere as $5, there is now an issue with tax calculation, as it continues to be computed based on the original price (e.g., $4.49) rather than the updated $5.
Example:
Cart total is $10 from 2 products that are each $5.
But tax of 19% shown is as $1,60 because it is still calculated based on the $4,49 original price. Goal would be to have the 19% tax calculated on the changed prices that would be $1,90 from the $10 in this example.
The objective is to resolve this inconsistency and ensure that the tax is accurately calculated from the new fixed price of $5 for products falling below the $5 threshold.
This is my code that I currently use in function.php:
/* Changing the price of WordPress products dynamically by redpishi.com */
function filtering_product_prices( $price, $product ) {
$price = (float)$price;
$new_price = $price * 1 ; // New price formula
// paste conditional codes here
if ( $price < 5 ) {
return 5;
}
return ceil($new_price);
}
function custom_price( $price, $product ) {
wc_delete_product_transients($product->get_id());
return filtering_product_prices( $price, $product );
}
function custom_variation_price( $price, $variation, $product ) {
wc_delete_product_transients($variation->get_id());
return filtering_product_prices( $price, $product );
}
add_filter('woocommerce_product_get_price', 'custom_price', 90, 2 );
add_filter('woocommerce_product_get_tax_price', 'custom_price', 90, 2 );
// add_filter('woocommerce_product_get_regular_price', 'custom_price', 90, 2 );
// add_filter('woocommerce_product_variation_get_regular_price', 'custom_price', 99, 2 );
// add_filter('woocommerce_product_variation_get_price', 'custom_price' , 99, 2 );
// add_filter('woocommerce_variation_prices_price', 'custom_variation_price', 99, 3 );
// add_filter('woocommerce_variation_prices_regular_price', 'custom_variation_price', 99, 3 );
Tax is calculated with Germanized Pro plugin.
Any hero out that that can help me to get tax calculated right for the above code?
Thank you already very much!
I don't think it's a good idea to "overwrite" prices like that on the front end only. You could use
woocommerce_before_calculate_totalshook to recalculate everything during checkout, but I suspect there might be other places where the old price below $5 will persist, especially while using plugin likeGermanized Pro.I don't know your specific case but if you don't actually need the old prices for some future use I would suggest simply batch editing products on
Woocommerceadmin. If for some reason sorting them by price is problematic you can use more advanced solution likeBulk Table Editor.