Skip to content

Instantly share code, notes, and snippets.

@goranefbl
Last active January 15, 2025 12:43
Show Gist options
  • Save goranefbl/206c5e3bd042b7fcfd4bfbb3e9d572af to your computer and use it in GitHub Desktop.
Save goranefbl/206c5e3bd042b7fcfd4bfbb3e9d572af to your computer and use it in GitHub Desktop.
Accumulate coupons into single coupon
<?php
// Hook the function to the filter
add_filter('gens_raf_coupon_amount', 'modify_raf_coupon_amount', 10, 2);
function modify_raf_coupon_amount($amount, $order_id) {
// Get the user email from the order
$order = wc_get_order($order_id);
if (!$order) return $amount;
$rafID = get_post_meta($order_id,'_wpgens_raf_id',true);
if(!$rafID) {
$rafID = $order->get_meta('_wpgens_raf_id');
}
// Determine the user email
if (filter_var($rafID, FILTER_VALIDATE_EMAIL)) {
$user_email = $rafID; // This is already an email
} else {
$gens_users = get_users(array(
"meta_key" => "gens_referral_id",
"meta_value" => $rafID,
"number" => 1,
"fields" => array("ID", "user_email")
));
if (is_array($gens_users) && !empty($gens_users)) {
$user_email = $gens_users[0]->user_email;
} else {
// If we can't determine the email, return the original amount
return $amount;
}
}
// Find existing RAF coupons for this user
$args = array(
'posts_per_page' => -1,
'post_type' => 'shop_coupon',
'meta_query' => array(
array(
'key' => 'customer_email',
'value' => $user_email,
'compare' => '=',
),
),
);
$existing_coupons = get_posts($args);
$total_amount = floatval($amount);
$coupons_to_delete = array();
foreach ($existing_coupons as $coupon) {
if (strpos($coupon->post_title, 'RAF-') === 0) {
$coupon_amount = get_post_meta($coupon->ID, 'coupon_amount', true);
$total_amount += floatval($coupon_amount);
$coupons_to_delete[] = $coupon->ID;
}
}
// Delete the existing RAF coupons
foreach ($coupons_to_delete as $coupon_id) {
wp_delete_post($coupon_id, true);
}
return $total_amount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment