Skip to content

Instantly share code, notes, and snippets.

@Lonsdale201
Created July 29, 2024 10:56
Show Gist options
  • Save Lonsdale201/ced7fcb022ca6f3839c5ec4a43c313e8 to your computer and use it in GitHub Desktop.
Save Lonsdale201/ced7fcb022ca6f3839c5ec4a43c313e8 to your computer and use it in GitHub Desktop.
Dynamic coupon for wc by exit intent custom popup (beta)
// place the code in the child theme functions.php or a custom code snippets plugin, like FluentSnippets
// Define the coupon discount rate
define('COUPON_DISCOUNT_RATE', 10); // 10% discount
// Enqueue custom script for exit intent detection
function enqueue_exit_intent_script() {
if (is_cart() || is_checkout()) {
?>
<script>
jQuery(document).ready(function($) {
var exitIntentShown = false;
$(document).mouseleave(function(e) {
if (e.clientY < 10 && !exitIntentShown) {
exitIntentShown = true;
$('#exit-intent-popup').fadeIn();
}
});
$('#exit-intent-close').click(function() {
$('#exit-intent-popup').fadeOut();
});
$('#apply-coupon').click(function() {
var couponCode = $('#coupon-code').text();
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: {
action: 'apply_virtual_coupon',
coupon_code: couponCode,
security: '<?php echo wp_create_nonce('apply_virtual_coupon_nonce'); ?>'
},
success: function(response) {
if (response.success) {
alert('A kupon sikeresen alkalmazva!');
document.cookie = "used_coupon=true; path=/";
document.cookie = "virtual_coupon=" + couponCode + "; path=/";
$('#exit-intent-popup').fadeOut();
location.reload();
} else {
alert(response.data.message);
}
}
});
});
});
</script>
<?php
}
}
add_action('wp_footer', 'enqueue_exit_intent_script');
// Add popup HTML to cart and checkout pages
function add_exit_intent_popup() {
if ((is_cart() || is_checkout()) && WC()->cart->get_cart_contents_count() > 0 && !has_used_coupon()) {
$coupon_code = generate_virtual_coupon();
?>
<div id="exit-intent-popup" style="display:none; position:fixed; top:30%; left:30%; width:40%; padding:20px; background:#fff; border:2px solid #000; z-index:1000; text-align:center;">
<p>Biztos? És további <?php echo COUPON_DISCOUNT_RATE; ?>% kedvezménnyel vásárolhatod meg a termékeket.</p>
<p>Kedvezmény kód: <strong id="coupon-code"><?php echo esc_html($coupon_code); ?></strong></p>
<button id="apply-coupon">Kupon alkalmazása</button>
<button id="exit-intent-close">Bezár</button>
</div>
<?php
error_log('Popup displayed with coupon code: ' . $coupon_code);
}
}
add_action('wp_footer', 'add_exit_intent_popup');
// Generate a virtual coupon
function generate_virtual_coupon() {
$coupon_code = 'VIRTUAL-' . wp_generate_password(8, false);
setcookie('virtual_coupon', $coupon_code, time() + 3600, "/");
error_log('Generated virtual coupon: ' . $coupon_code);
return $coupon_code;
}
// Check if user has used the coupon
function has_used_coupon() {
$used_coupon = isset($_COOKIE['used_coupon']) && $_COOKIE['used_coupon'] === 'true';
error_log('Checked used coupon: ' . ($used_coupon ? 'true' : 'false'));
return $used_coupon;
}
// Handle AJAX request to apply virtual coupon
function apply_virtual_coupon() {
check_ajax_referer('apply_virtual_coupon_nonce', 'security');
if (isset($_POST['coupon_code']) && isset($_COOKIE['virtual_coupon']) && sanitize_text_field($_POST['coupon_code']) === $_COOKIE['virtual_coupon']) {
$coupon_code = sanitize_text_field($_POST['coupon_code']);
error_log('Applying coupon code: ' . $coupon_code);
$args = array(
'post_type' => 'shop_coupon',
'post_status' => 'publish',
'title' => $coupon_code,
'posts_per_page' => 1
);
$existing_coupon_query = new WP_Query($args);
if ($existing_coupon_query->have_posts()) {
error_log('Coupon already exists: ' . $coupon_code);
wp_send_json_error(array('message' => 'Coupon already exists.'));
}
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_excerpt' => 'Virtuális kupon ' . COUPON_DISCOUNT_RATE . '% kedvezmény',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post($coupon);
error_log('Created new coupon with ID: ' . $new_coupon_id);
update_post_meta($new_coupon_id, 'discount_type', 'percent');
update_post_meta($new_coupon_id, 'coupon_amount', COUPON_DISCOUNT_RATE);
update_post_meta($new_coupon_id, 'individual_use', 'yes');
update_post_meta($new_coupon_id, 'usage_limit', '1');
update_post_meta($new_coupon_id, 'expiry_date', date('Y-m-d', strtotime('+1 day')));
update_post_meta($new_coupon_id, 'apply_before_tax', 'yes');
update_post_meta($new_coupon_id, 'free_shipping', 'no');
// Apply the coupon to the cart
$result = WC()->cart->apply_coupon($coupon_code);
if ($result) {
error_log('Coupon applied to cart: ' . $coupon_code);
} else {
error_log('Failed to apply coupon to cart: ' . $coupon_code);
}
// Set cookies via server-side to ensure security
setcookie('used_coupon', 'true', time() + 3600, "/");
setcookie('virtual_coupon', $coupon_code, time() + 3600, "/");
wp_send_json_success(array(
'message' => 'Coupon applied successfully',
'coupon_code' => $coupon_code
));
} else {
error_log('Invalid coupon code or no matching cookie found.');
wp_send_json_error(array('message' => 'Invalid coupon code.'));
}
}
add_action('wp_ajax_apply_virtual_coupon', 'apply_virtual_coupon');
add_action('wp_ajax_nopriv_apply_virtual_coupon', 'apply_virtual_coupon');
// Add a function to check if the coupon was removed and reset the cookies
function check_coupon_removal() {
if (is_cart() || is_checkout()) {
if (isset($_COOKIE['used_coupon']) && $_COOKIE['used_coupon'] === 'true') {
if (!empty($_COOKIE['virtual_coupon']) && !WC()->cart->has_discount($_COOKIE['virtual_coupon'])) {
error_log('Coupon removed from cart: ' . $_COOKIE['virtual_coupon']);
setcookie('used_coupon', '', time() - 3600, "/");
setcookie('virtual_coupon', '', time() - 3600, "/");
error_log('Cookies reset.');
}
}
}
}
add_action('template_redirect', 'check_coupon_removal');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment