Custom Coupon For Woocommerce

PHOTO EMBED

Tue Aug 06 2024 11:00:28 GMT+0000 (Coordinated Universal Time)

Saved by @ngoctran #php

function woo_checkout_custom_coupon_form(){
	if ( ! wc_coupons_enabled() ) { // @codingStandardsIgnoreLine.
		return;
	}
?>
<div class="mini-cart-nm-coupon">
	<div class="mini-cart-nm-coupon-heading">Enter your discount code</div>
    <div class="nm-coupon" style="display: flex;">
       <input type="text" id="nm-coupon-code" class="input-text nm-coupon-code" name="nm_coupon_code" value="" placeholder="">
       <button type="button" id="nm-apply-coupon-btn" class="button" name="nm_apply_coupon" value="" onclick="applyCoupon(this)" style="white-space: nowrap;"><?php esc_html_e( 'ACTIVATE', 'woocommerce' ); ?></button>
    </div>
    <div class="nm-coupon-notify" style="display: none; color: #FF0000;"></div>
</div>
<script type="text/javascript">
function applyCoupon(button) {
    let form = button.closest('.nm-coupon');
	button.innerText = 'ACTIVATE...';
    let couponCode = form.querySelector(".nm-coupon-code").value;
    let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    
    jQuery.ajax({
        type: "GET",
        url: ajaxurl,
        dataType: 'json',
        data: 'coupon_code=' + couponCode + '&action=custom_apply_coupon',
        success: function (data) {
            if (data.status === 'success') {
                jQuery(document.body).trigger('wc_fragment_refresh');
                
            } else if (data.status === 'already_used') {
                jQuery('.nm-coupon-notify').html('Coupon already used!');
                jQuery('.nm-coupon-notify').show();
            } else {
                jQuery('.nm-coupon-notify').html('Coupon is not valid!');
                jQuery('.nm-coupon-notify').show();
            }
			if (jQuery('body').hasClass('woocommerce-checkout'))
                    jQuery(document.body).trigger('update_checkout');
        },
    });
}
// Remove coupon script
(function($) {
    $('body').on('click', '.woocommerce-remove-coupon', function(e) {
        e.preventDefault();
        let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        var coupon = $(this).data('coupon');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'remove_coupon',
                coupon: coupon,
            },
            success: function(response) {
                jQuery(document.body).trigger('wc_fragment_refresh');
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    });
})(jQuery);	
</script>
<?php    
}
add_action( 'woo_custom_checkout_coupon_form', 'woo_checkout_custom_coupon_form',10 );

add_action('wp_ajax_custom_apply_coupon', 'custom_apply_coupon');
add_action('wp_ajax_nopriv_custom_apply_coupon', 'custom_apply_coupon');

function custom_apply_coupon() {
    $coupon_code = isset($_GET['coupon_code']) ? $_GET['coupon_code'] : '';
    $coupon_code = sanitize_text_field($coupon_code);

    // Check if the coupon is already applied
    if (WC()->cart->has_discount($coupon_code)) {
        echo json_encode(array('status' => 'already_used'));
    } else {
        // Apply coupon
        $applied = WC()->cart->apply_coupon($coupon_code);
        if ($applied) {
            echo json_encode(array('status' => 'success'));
        } else {
            echo json_encode(array('status' => 'invalid'));
        }
    }
    wp_die();
}

add_action('wp_ajax_remove_coupon', 'remove_coupon_from_cart');
add_action('wp_ajax_nopriv_remove_coupon', 'remove_coupon_from_cart');

function remove_coupon_from_cart() {
    if (isset($_POST['coupon'])) {
        $coupon_code = sanitize_text_field($_POST['coupon']);
        WC()->cart->remove_coupon($coupon_code);
        wc_clear_notices(); 
        
        wp_send_json_success();
    } else {
        wp_send_json_error('Coupon code not provided.');
    }
}
content_copyCOPY