Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Created May 29, 2019 04:48
Show Gist options
  • Save MogulChris/c2ff838005d9352b5164552e69be46a9 to your computer and use it in GitHub Desktop.
Save MogulChris/c2ff838005d9352b5164552e69be46a9 to your computer and use it in GitHub Desktop.
Easy WooCommerce global store discounts
<?php
//We will use this function to modify prices whenever WooCommerce retrieves them
function mytheme_global_sale_price( $price, $product ) {
$product_id = $product->get_id();
//do any checks you need to exclude or include products here
$excluded_products = [123,678];
if(in_array($product_id, $excluded_products)) return $price;
//I am using a custom field to provide an on/off toggle for the global discount, and another for the percentage discount. You could alternatively just hard-code these.
$global_discount_enabled = get_field('enable_global_discount','option');
if($global_discount_enabled){
$discount_amount = get_field('global_discount_percent', 'option'); //returns an integer eg 30 for a 30% discount
if(empty($discount_amount)) return $price;
//calculate the discounted price
$price = $price - ($price * ($discount_amount / 100));
}
return $price;
}
//We are using hooks for the 'price' and 'sale price'
//Note this means any sale prices will be further discounted by the global discount. Comment out the sale price hooks if you don't want that.
add_filter( 'woocommerce_get_price', 'mytheme_global_sale_price', 10, 2 );
add_filter( 'woocommerce_get_sale_price', 'mytheme_global_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'mytheme_global_sale_price', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'mytheme_global_sale_price', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment