Last active
August 14, 2024 11:38
-
-
Save braddalton/eaddb2e509961be227da0fc6189c3dbd to your computer and use it in GitHub Desktop.
Once the user completes 5 purchases, the code automatically applies a discount to their 6th purchase. After applying the discount, the order count resets.
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
add_action('woocommerce_order_status_completed', 'track_completed_orders_101', 10, 1); | |
function track_completed_orders_101($order_id) { | |
$order = wc_get_order($order_id); | |
$user_id = $order->get_user_id(); | |
if ($user_id) { | |
$completed_orders = get_user_meta($user_id, '_completed_orders_count', true); | |
$completed_orders = $completed_orders ? $completed_orders + 1 : 1; | |
update_user_meta($user_id, '_completed_orders_count', $completed_orders); | |
} | |
} | |
add_action('woocommerce_cart_calculate_fees', 'apply_sixth_purchase_discount_101'); | |
function apply_sixth_purchase_discount_101() { | |
if (is_admin() && !defined('DOING_AJAX')) return; | |
$user_id = get_current_user_id(); | |
if ($user_id) { | |
$completed_orders = get_user_meta($user_id, '_completed_orders_count', true); | |
if ($completed_orders >= 5) { | |
$discount_percentage = 10; // Set the discount percentage here | |
$discount = WC()->cart->get_subtotal() * ($discount_percentage / 100); | |
WC()->cart->add_fee('Loyalty Discount', -$discount); | |
} | |
} | |
} | |
add_action('woocommerce_order_status_completed', 'reset_order_count_after_discount_101', 20, 1); | |
function reset_order_count_after_discount_101($order_id) { | |
$order = wc_get_order($order_id); | |
$user_id = $order->get_user_id(); | |
if ($user_id) { | |
$completed_orders = get_user_meta($user_id, '_completed_orders_count', true); | |
if ($completed_orders == 6) { | |
update_user_meta($user_id, '_completed_orders_count', 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment