在WooCommerce结账前的强制优惠券(可选:针对特定产品) [英] Mandatory coupon before checkout in WooCommerce (optional: for specific products)

查看:0
本文介绍了在WooCommerce结账前的强制优惠券(可选:针对特定产品)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想强制客户在可以结账之前添加优惠券代码。我希望它能与我的WooCommerce商店中的每个优惠券代码和每一种产品一起使用。

我正在使用这个代码,它几乎解决了问题,但它只对单个优惠券代码(freev1)起作用

如何才能对生成的每个优惠券代码都起作用?

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
function mandatory_coupon_code() {
    // HERE set your coupon code
    $mandatory_coupon = 'freev1';

    $applied_coupons = WC()->cart->get_applied_coupons();

    // If coupon is found we exit
    if( in_array( $mandatory_coupon, $applied_coupons ) ) return;

    // Not found: display an error notice
    wc_add_notice( __( 'Add coupon before checkout.', 'woocommerce' ), 'error' );
}

推荐答案

只检查$applied_coupons是否为空,如果为空则添加通知。删除$mandatory_couponif ( in_array...

(&A)

因此您得到:

function action_woocommerce_check_cart_items() {
    // Isset
    if ( WC()->cart ) {
        // Get applied coupons
        $applied_coupons = WC()->cart->get_applied_coupons();

        // When empty
        if ( empty ( $applied_coupons ) ) {
            // Not found: display an error notice
            wc_add_notice( __( 'Add coupon before checkout.', 'woocommerce' ), 'error' );   
        }
    }
}
add_action( 'woocommerce_check_cart_items', 'action_woocommerce_check_cart_items', 10 );

更新:

要将其应用于购物车中的特定产品,请使用:

function action_woocommerce_check_cart_items() {
    // The targeted product ids
    $targeted_ids = array( 30, 815 );

    // Flag
    $found = false;
    
    // Isset
    if ( WC()->cart ) {
        // Get applied coupons
        $applied_coupons = WC()->cart->get_applied_coupons();

        // When empty
        if ( empty ( $applied_coupons ) ) {
            // Loop through cart items
            foreach ( WC()->cart->get_cart() as $cart_item ) {
                if ( array_intersect( $targeted_ids, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
                    $found = true;
                    break;
                }
            }
        }
    }
    
    // True
    if ( $found ) {
        // Not found: display an error notice
        wc_add_notice( __( 'Add coupon before checkout.', 'woocommerce' ), 'error' );
    }
}
add_action( 'woocommerce_check_cart_items', 'action_woocommerce_check_cart_items', 10 );

其他问题:

是否可以使用几乎相同的代码,而是使其在结账页面上工作并强制使用优惠券(&P>) 下单?

可以将woocommerce_check_cart_items替换为 woocommerce_checkout_process结账页的挂钩

这篇关于在WooCommerce结账前的强制优惠券(可选:针对特定产品)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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