Untitled
unknown
plain_text
a year ago
2.0 kB
12
Indexable
<?php
// Function to set the coupon code cookie
function set_coupon_code_cookie() {
// Check if the apply_cpncd parameter is set in the URL.
if (isset($_GET['apply_cpncd'])) {
$coupon_code = sanitize_text_field($_GET['apply_cpncd']);
// Set a cookie for 1 day. Adjust the time as needed.
setcookie('apply_cpncd', $coupon_code, time() + (86400 * 1), COOKIEPATH, COOKIE_DOMAIN);
}
}
add_action('init', 'set_coupon_code_cookie');
// Enqueue jQuery script for applying coupon in WooCommerce
function apply_coupon_code_script() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
// Function to read a cookie's value
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
// Read the apply_cpncd cookie
var couponCode = readCookie('apply_cpncd');
if (couponCode) {
var data = {
action: 'woocommerce_apply_coupon',
security: wc_checkout_params.apply_coupon_nonce,
coupon_code: couponCode
};
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: data,
success: function(response) {
if (response) {
console.log("Coupon applied successfully");
// Optionally, reload the page to show the applied coupon.
// location.reload();
}
},
dataType: 'html'
});
}
});
</script>
<?php
}
add_action('wp_footer', 'apply_coupon_code_script');
?>Editor is loading...
Leave a Comment