3

I have a small project on what I need to insert Woocommerce coupon field into any page, but this seems complicated for me. I searched on Google about this, but don't have any resources about this. Found this codes about inserting field.

Inserted into a text block this code:

<div class="redeem-coupon">
<form id="ajax-coupon-redeem">
    <p>
        <input type="text" name="coupon" id="coupon"/>
        <input type="submit" name="redeem-coupon" value="Redeem Offer" />
    </p>
    <p class="result"></p>
</form><!-- #ajax-coupon-redeem -->

And this generate the form, but don't have other code that will handle this into page?

Is possible to generate via shortcode or something?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Bern
  • 65
  • 2
  • 10

1 Answers1

8

The following custom Shortcode, will display a text imput field (with a submit button) where user can enter a coupon code to be applied.

Usage: [coupon_field] or in Php code echo do_shortcode("[coupon_field]");

The code:

add_shortcode( 'coupon_field', 'display_coupon_field' );
function display_coupon_field() {
    if( isset($_GET['coupon']) && isset($_GET['redeem-coupon']) ){
        if( $coupon = esc_attr($_GET['coupon']) ) {
            $applied = WC()->cart->apply_coupon($coupon);
        } else {
            $coupon = false;
        }

        $success = sprintf( __('Coupon "%s" Applied successfully.'), $coupon );
        $error   = __("This Coupon can't be applied");

        $message = isset($applied) && $applied ? $success : $error;
    }

    $output  = '<div class="redeem-coupon"><form id="coupon-redeem">
    <p><input type="text" name="coupon" id="coupon"/>
    <input type="submit" name="redeem-coupon" value="'.__('Redeem Offer').'" /></p>';

    $output .= isset($coupon) ? '<p class="result">'.$message.'</p>' : '';

    return $output . '</form></div>';
}

Code goes on function.php file of your active child theme (or theme). Tested and works.

It displays a success or an error message, once applying a coupon.

enter image description here

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399