Change WooCommerce product and variation prices programatically without affecting performance
I need to set a global 5% discount (or 0.95 margin) for all logged in customers on my store. I've used filters to alter the price for all simple products and product variations. To get it working correctly I needed to delete product transients of each product for logged in users.
This works well but the loading time is way too long. The performance impact of this seems to be drastic.
Here's the code:
function change_price_for_logged_in_customers($price, $product, $clear_transients) {
if ( is_user_logged_in() is_numeric($price) ) {
// Clear WC transients for variations
if($clear_transients) {
wc_delete_product_transients($product-get_id());
}
// Apply 5% discount, round up discounted price to 1 decimal
$logged_in_price = $price*0.95;
$logged_in_price = number_format((float)$logged_in_price, 1, '.', '');
return $logged_in_price;
}
return $price;
}
function logged_in_discount_filter($price, $product) {
return change_price_for_logged_in_customers($price, $product, 0);
}
add_filter('woocommerce_product_get_price', 'logged_in_discount_filter', 10, 2);
function custom_price( $price, $product ) {
return change_price_for_logged_in_customers($price, $product, 1);
}
add_filter('woocommerce_product_variation_get_price', 'custom_price' , 99, 2 );
function custom_variation_price( $price, $variation, $product ) {
return change_price_for_logged_in_customers($price, $product, 1);
}
add_filter('woocommerce_variation_prices_price', 'custom_variation_price', 99, 3 );
Is there a way to do this more efficiently?
Thank you
Topic woocommerce-offtopic transient Wordpress performance
Category Web