Last active
May 31, 2021 12:24
-
-
Save FrancoStino/557307b1ea23993ba776afd0a95a2fe3 to your computer and use it in GitHub Desktop.
Discount as fee at first order exclude product on sale and if is applied a coupon disable fee
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Discount as fee at first order exclude product on sale and if is applied a coupon disable fee | |
*/ | |
add_action('woocommerce_cart_calculate_fees' , 'custom_discount', 10, 1); | |
function custom_discount( $cart ){ | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) || ! is_user_logged_in() ) | |
return; | |
// Getting "completed" customer orders | |
$customer_orders = get_posts( array( | |
'numberposts' => -1, | |
'meta_key' => '_customer_user', | |
'meta_value' => get_current_user_id(), | |
'post_type' => 'shop_order', // WC orders post type | |
'post_status' => 'wc-completed' // Only orders with status "completed" | |
) ); | |
// Orders count | |
$customer_orders_count = count($customer_orders); | |
// Initialising variable | |
$is_on_sale = false; | |
// Iterating through each item in cart | |
foreach( $cart->get_cart() as $cart_item ){ | |
// Getting an instance of the product object | |
$product = $cart_item['data']; | |
// If a cart item is on sale, $is_on_sale is true and we stop the loop | |
if($product->is_on_sale()){ | |
$is_on_sale = true; | |
break; | |
} | |
} | |
## Discount calculation ## | |
$discount = (-10 / 100) * WC()->cart->get_subtotal(); // or WC()->cart->get_total_ex_tax() | |
## Applied discount (no products on sale) ## | |
if(!$is_on_sale AND empty($customer_orders) || $customer_orders_count == 0){ | |
$cart->add_fee( 'Sconto sul primo ordine', $discount); | |
} | |
## Se c'è un coupon nel carrello disabilita la tassa ## | |
elseif( ( is_cart() || is_checkout() ) && sizeof( WC()->cart->get_applied_coupons() ) > 0){ | |
$cart->fees_api()->set_fees($fees); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment