Skip to content

Instantly share code, notes, and snippets.

@Frisoni
Forked from rwkyyy/EVD Cart Discount Rules
Last active February 2, 2022 18:18
Show Gist options
  • Save Frisoni/0e682a5d30a4398569df63fb1a2d09ca to your computer and use it in GitHub Desktop.
Save Frisoni/0e682a5d30a4398569df63fb1a2d09ca to your computer and use it in GitHub Desktop.
WooCommerce conditional subtotal cart discounts
<?php
/**
* Plugin Name: EVD - Card Discount Rules
* Plugin URI: https://rwky.ro
* Description: Discount rules for cart
* Version: 1.0
* Author: Eduard Vasile Doloc
* Author URI: http://rwky.ro
* Developer: Eduard Vasile Doloc
* Developer URI: http://rwky.ro
* Text Domain: evd_discounts
* Domain Path: /languages
*
* WC requires at least: 2.2
* WC tested up to: 3.3.5
*
* License: GNU General Public License v3.0
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
/**
* Check if WooCommerce is active - we don't want that, do we?
**/
function evd_woo_is_absent() {
if (!defined('WC_VERSION')) {
?>
<div class="error notice">
<p>
<?php _e( 'EVD Cart Discount Rules - <strong>WooCommerce is not active!</strong>', 'evd_discounts' ); ?>
</p>
</div>
<?php
}
}
add_action( 'admin_notices', 'woo_is_absent' );
// Magic & logic
add_action('woocommerce_cart_calculate_fees', 'evd_woo_discounts');
function evd_woo_discounts() {
global $woocommerce;
$excluded_amount = $discount_percent = 0;
// Calculate working total based on regular prices
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
$working_total += $cart_item['quantity'] * $product->get_regular_price();
}
# Only apply manual discount if no coupons are applied
if (!$woocommerce->cart->applied_coupons) {
# Logic to determine WHICH discount to apply based on subtotal
if ($working_total >= 2400) {
$discount_percent = 40;
}
else {
$discount_percent = 0;
}
# Make sure cart total is eligible for discount
if ($discount_percent > 0) {
$discount_amount = ( ( ($discount_percent/100) * $working_total ) * -1 );
$woocommerce->cart->add_fee('Discount', $discount_amount);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment