微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 即使在WooCommerce中购物车为空,也可以通过URL中的GET方法应用优惠券折扣

我有一个插件,可以向他们输入的电子邮件发送支持者推荐优惠券代码.当观众收到这封电子邮件时,我想创建一个流程,他们可以点击电子邮件中的“立即购物”,优惠券将自动添加.

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

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

You can set any existing coupon code from any Url (like shop page, other archives pages, products pages, my account pages, or any existing pages) adding to this existing url:
?code=disCOUNTCODE at the end
(where disCOUNTCODE is your coupon code name).

这是代码

// 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', 10, 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文件中或任何插件文件中.

这是经过测试和运作的

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐