Display a WooCommerce coupon input field anywhere with a shortcode

怎甘沉沦 提交于 2019-12-22 23:26:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/55247087/display-a-woocommerce-coupon-input-field-anywhere-with-a-shortcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!