-1

Based on Move coupon form before payment section in WooCommerce checkout answer code. I'm customizing the Woocommerce checkout page, moving the coupon code field on different location.

Now the biggest problem is that I can't find a way to move coupon related errors below coupon field. If there is an error (for example, when a coupon is not valid) I want to show new div below coupon-form div displaying the error.

Here is My code:

// Just hide default woocommerce coupon field
add_action( 'woocommerce_before_checkout_form', 'hide_checkout_coupon_form', 5 );
function hide_checkout_coupon_form() {
echo '<style>.woocommerce-form-coupon-toggle {display:none;}</style>';
}

// Add a custom coupon field before checkout payment section
add_action( 'woocommerce_review_order_before_payment', 
'woocommerce_checkout_coupon_form_custom' );
function woocommerce_checkout_coupon_form_custom() {

 echo '<div class="coupon-form" style="margin-bottom:20px;" style="display:none !important;">

        <input type="text" name="coupon_code" class="input-text" placeholder="' . __("Coupon code") . '" id="coupon_code" value="">
        <button type="button" class="button coupon-btn" name="apply_coupon" value="' . __("Apply coupon") . '">' . __("Apply coupon") . '</button>

    <div class="clear"></div>
    
</div>';
}

// jQuery code
add_action( 'wp_footer', 'custom_checkout_jquery_script' );
function custom_checkout_jquery_script() {
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script type="text/javascript">
jQuery( function($){

    
    // Copy the inputed coupon code to WooCommerce hidden default coupon field
    $('.coupon-form input[name="coupon_code"]').on( 'input change', function(){
        $('form.checkout_coupon input[name="coupon_code"]').val($(this).val());
        // console.log($(this).val()); // Uncomment for testing
    });
    
    // On button click, submit WooCommerce hidden default coupon form
    $('.coupon-form button[name="apply_coupon"]').on( 'click', function(){
        $('form.checkout_coupon').submit();
        // console.log('click: submit form'); // Uncomment for testing
    });
});

(function($){

    $('.woocommerce-form-coupon-toggle').remove();
    $(document).on("click", 'button[name="apply_coupon"]', function(event) {
        
        event.preventDefault();

        $form = $('form[name="checkout"]');
        $form.block({message:''});

        var data = {
            security:       wc_checkout_params.apply_coupon_nonce,
            coupon_code:    $( 'input[name="coupon_code"]' ).val()
        };

        $.ajax({
            type:       'POST',
            url:        wc_checkout_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'apply_coupon' ),
            data:       data,
            success:    function( code ) {
                
                $( '.woocommerce-error, .woocommerce-message' ).remove();
                $form.removeClass( 'processing' ).unblock();

                if ( code ) {
                    $( 'button[name="apply_coupon"]' ).parent().after( code );
                    $( document.body ).trigger( 'update_checkout', { update_shipping_method: false } );
                }

            },
            dataType: 'html'
        });

    });

})(jQuery);
</script>
<?php
endif;
}

In one of my favorite themes I found this piece of code and I tried to replace my code with it, but can not make it work

        apply_coupon: function (t) {
        this.$review.is(".--loading") || this.$review.parents(".--loading").length || this.$review.addClass("--loading");
        var i = this,
            o = t.siblings("input[name='coupon_code']"),
            n = o.val(),
            s = { security: wc_checkout_params.apply_coupon_nonce, coupon_code: n };
        e.ajax({
            type: "POST",
            url: wc_checkout_params.wc_ajax_url.toString().replace("%%endpoint%%", "apply_coupon"),
            data: s,
            dataType: "html",
            success: function (o) {
                e(".woocommerce-error, .woocommerce-message, .woocommerce-info", this.$page).remove(), e(".__notice", this.$page).remove();
                var n = e('<div class="__notice --clean-wc-notice">' + o + "</div>").insertAfter(t.parent());
                e(document.body).trigger("applied_coupon_in_checkout", [s.coupon_code]),
                    e(document.body).trigger("update_checkout", { update_shipping_method: !1 }),
                    e(".woocommerce-message", n).length && i.$review.addClass("--mob-active");
            },
            complete: function () {
                i.$review.removeClass("--loading"), o.val("");
            },
        });
    },
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Karnak
  • 21
  • 2
  • 7
  • 21

1 Answers1

1

To display coupon-related errors below the coupon field on the WooCommerce checkout page, you can modify the existing cod

// Just hide default WooCommerce coupon field
add_action( 'woocommerce_before_checkout_form', 'hide_checkout_coupon_form', 5 );
function hide_checkout_coupon_form() {
    echo '<style>.woocommerce-form-coupon-toggle {display:none;}</style>';
}
// Add a custom coupon field before checkout payment section
add_action( 'woocommerce_review_order_before_payment', 'woocommerce_checkout_coupon_form_custom' );
function woocommerce_checkout_coupon_form_custom() {
    echo '<div class="coupon-form" style="margin-bottom:20px;" style="display:none !important;">
        <input type="text" name="coupon_code" class="input-text" placeholder="' . __("Coupon code") . '" id="coupon_code" value="">
        <button type="button" class="button coupon-btn" name="apply_coupon" value="' . __("Apply coupon") . '">' . __("Apply coupon") . '</button>
        <div class="coupon-error"></div>
        <div class="clear"></div>
    </div>';
}
// jQuery code
add_action( 'wp_footer', 'custom_checkout_jquery_script' );
function custom_checkout_jquery_script() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
        jQuery( function($){
            // Copy the inputted coupon code to WooCommerce hidden default coupon field
            $('.coupon-form input[name="coupon_code"]').on( 'input change', function(){
                $('form.checkout_coupon input[name="coupon_code"]').val($(this).val());
            });
            // On button click, submit WooCommerce hidden default coupon form
            $('.coupon-form button[name="apply_coupon"]').on( 'click', function(){
                $('form.checkout_coupon').submit();
            });
            // Handle coupon application response
            $(document.body).on('applied_coupon_in_checkout', function(event, coupon_code){
                if (coupon_code) {
                    $('.coupon-error').html('');
                }
            });
            $(document.body).on('woocommerce-applied_coupon-in_checkout', function(event, response){
                if (response && response.result === 'failure' && response.messages) {
                    $('.coupon-error').html(response.messages);
                }
            });
        });
    </script>
    <?php
    endif;
}
Heidar Ammarloo
  • 421
  • 2
  • 11
  • Hi, Heidar Ammarloo! You posted 9 answers in June that appear likely to be entirely or partially written by AI (e.g., ChatGPT), with *five* of these having comments that said that the answer didn't work. Please be aware that [posting AI-generated content is not allowed here](//meta.stackoverflow.com/q/421831). If you used an AI tool to assist with any answer, I would encourage you to delete it. We do hope you'll stick around and continue to be a valuable part of our community by posting *your own* quality content. Thanks! – NotTheDr01ds Jul 23 '23 at 12:00
  • **Readers should review this answer carefully and critically, as AI-generated information often contains fundamental errors and misinformation.** If you observe quality issues and/or have reason to believe that this answer was generated by AI, please leave feedback accordingly. – NotTheDr01ds Jul 23 '23 at 12:00