通过URL获取优惠券代码并将其应用于WooCommerce Checkout页面 [英] GET a coupon code via URL and apply it in WooCommerce Checkout page

查看:173
本文介绍了通过URL获取优惠券代码并将其应用于WooCommerce Checkout页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WooCommerce网站,当客户将其添加到购物车中时,该产品将重定向到结帐页面,因此无法访问购物车页面.

I have a WooCommerce website and when customer add-to-cart a product, it is get redirected to checkout page, so cart page is not accessible.

我想通过结帐页面上的URL(GET)申请优惠券,例如https://example.com/?coupon_code=highfive.

I would like to apply coupon via URL (GET) on checkout page, with something like https://example.com/?coupon_code=highfive.

当客户单击此URL时,优惠券代码将存储在浏览器会话中.然后,如果他将其添加到购物车中,则可以将优惠券应用到结帐页面.

When customer click this URL then the coupon code is stored in browser sessions. Then if he add-to-cart any product then the coupon is applied into checkout page.

这可能吗?

推荐答案

更新3:这可以通过以下两个挂钩函数以非常简单的方式完成:

Update 3: This can be done in a very simple way with the following 2 hooked functions:

  • 第一个将在Url中捕获优惠券代码,并将其设置在WC_Sessions中.
  • 第二个将在结帐页面中应用会话中的优惠券代码.

这是此代码:

add_action('init', 'get_custom_coupon_code_to_session');
function get_custom_coupon_code_to_session(){
    if( isset($_GET['coupon_code']) ){
        // Ensure that customer session is started
        if( !WC()->session->has_session() )
            WC()->session->set_customer_session_cookie(true);

        // Check and register coupon code in a custom session variable
        $coupon_code = WC()->session->get('coupon_code');
        if(empty($coupon_code)){
            $coupon_code = esc_attr( $_GET['coupon_code'] );
            WC()->session->set( 'coupon_code', $coupon_code ); // Set the coupon code in session
        }
    }
}

add_action( 'woocommerce_before_checkout_form', 'add_discout_to_checkout', 10, 0 );
function add_discout_to_checkout( ) {
    // Set coupon code
    $coupon_code = WC()->session->get('coupon_code');
    if ( ! empty( $coupon_code ) && ! WC()->cart->has_discount( $coupon_code ) ){
        WC()->cart->add_discount( $coupon_code ); // apply the coupon discount
        WC()->session->__unset('coupon_code'); // remove coupon code from session
    }
}

代码进入活动子主题(或活动主题)的function.php文件中.经过测试并有效

受此答案代码启发, Lukasz Wiktor 发布了一个插件:

Inspired from this answer code, Lukasz Wiktor has published a plugin: Woo Coupon URL

这篇关于通过URL获取优惠券代码并将其应用于WooCommerce Checkout页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆