php – 通过URL中的GET方法应用优惠券折扣,甚至在WooCommerce中清空购物车

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 通过URL中的GET方法应用优惠券折扣,甚至在WooCommerce中清空购物车脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个插件,可以向他们输入的邮件发送支持者推荐优惠券代码.当观众收到这封电子邮件时,我想创建一个流程,他们可以点击电子邮件中的“立即购物”,优惠券将自动添加.

截至目前,对于“立即购买”按钮下的链接,我输入了以下内容

websITename.biz/cart__trashed?code=DISCOUNTCODE

要处理$code,我把它放在我的functions.PHP文件中:

add_action('woocommerce_before_cart','discount');
function discount( ) {
    global $woocommerce;
    $code= $_GET["code"];
   if(!empty($code)){       
    if($woocommerce->cart->add_discount($code)){ 
    echo '<div class="woocommerce_message"><strong>Applied coupon!</strong></div>';
        }
    }
}

面临的问题是:

>如果观众访问网站时购物车中没有任何内容,优惠券将不会被应用.
>如果有一些东西被添加并留在那里(因为一个cookie),那么优惠券代码将被完美地应用.

我相信它是因为购物车是空的,代码不起作用.

只需要在受众点击链接时应用代码即可.

怎样才能使这个工作?

正确的方法应该是:

>将购物车会话中的URL中的优惠券代码设置为自定义数据.
>当客户将第一个商品添加到购物车时,应用此优惠券代码中的折扣.
>如果客户空车,请从此优惠券中删除折扣

这是代码

// Set coupon code as custom data in cart session
add_action('wp_loaded','add_coupon_code_to_cart_session');
function add_coupon_code_to_cart_session() {
    // Exit if no code in URL or if the coupon code is already set cart session
    if( empty( $_GET["code"] ) || WC()->session->get( 'custom_discount' ) ) return;

    if( ! WC()->session->get( 'custom_discount' ) ) {
        $coupon_code = esc_attr($_GET["code"]);
        WC()->session->set( 'custom_discount',$coupon_code );
        // If there is an existing non empty cart active session we apply the coupon
        if( ! WC()->cart->is_empty() ){
            WC()->cart->add_discount( $coupon_code );
        }
    }
}

// Add coupon code when a PRoduct is added to cart once
add_action('woocommerce_add_to_cart','add_coupon_code_to_cart',10,6 );
function add_coupon_code_to_cart( $cart_item_key,$product_id,$quantity,$VARiation_id,$variation,$cart_item_data ){
    $coupon_code = WC()->session->get( 'custom_discount' );
    $applied_coupons = WC()->session->get('applied_coupons');

    if( empty($coupon_code) || in_array( $coupon_code,$applied_coupons ) ) return;

    WC()->cart->add_discount( $coupon_code );
}

// Remove coupon code when user empty his cart
add_action('woocommerce_cart_item_removed','check_coupon_code_cart_items_removed',6 );
function check_coupon_code_cart_items_removed( $cart_item_key,$cart ){
    $coupon_code = WC()->session->get( 'custom_discount' );

    if( $cart->has_discount( $coupon_code ) && $cart->is_empty() );
        $cart->remove_coupon( $coupon_code );
}

代码位于活动主题(或活动主题)的function.PHP文件中或任何插件文件中.

这是经过测试和运作

脚本宝典总结

以上是脚本宝典为你收集整理的php – 通过URL中的GET方法应用优惠券折扣,甚至在WooCommerce中清空购物车全部内容,希望文章能够帮你解决php – 通过URL中的GET方法应用优惠券折扣,甚至在WooCommerce中清空购物车所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。