首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Woocommerce:特定产品的强制优惠券

Woocommerce:特定产品的强制优惠券
EN

Stack Overflow用户
提问于 2021-02-24 16:45:35
回答 1查看 276关注 0票数 2

基于Make coupon field mandatory for a product category in WooCommerce的答案,我试图在woocommerce实现特定产品的强制优惠券。

下面是我的代码尝试:

代码语言:javascript
运行
复制
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
    $targeted_ids = array(40, 41, 42, 43, 44); // The targeted product ids (in this array)
    $coupon_code = 'summer1, summer2, summer3, summer4, summer5'; // The required coupon code

    $coupon_applied = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() );

    // Loop through cart items
    foreach(WC()->cart->get_cart() as $cart_item ) {
        // Check cart item for defined product Ids and applied coupon
        if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) {
            wc_clear_notices(); // Clear all other notices
        
            // Avoid checkout displaying an error notice
            wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $cart_item['data']- 
            >get_name() ), 'error' );
            break; // stop the loop
        }
    }
}

代码完美地使优惠券成为强制性的,但我需要一个产品可以签出仅使用其中一张优惠券。

如果我将产品ID 40添加到购物车中,必须添加5张优惠券,summer1,summer2,summer3,summer3 4和summer5,否则结帐将是不可能的。我希望客户可以使用targeted_id数组中列出的任何产品的任何优惠券进行结帐。

换句话说,对于所有产品,优惠券的使用是强制性的,但不一定是特定的优惠券,可以是代码中列出的任何人。

例如,我列出了5种产品和5种优惠券,但实际上有100种产品和100种优惠券。

提前谢谢你

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-24 18:03:21

代码中有一些错误,请使用以下代码:

代码语言:javascript
运行
复制
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
    $targeted_ids  = array(40, 41, 42, 43, 44); // The targeted product ids (in this array)
    $coupon_codes  = array('summer1', 'summer2', 'summer3', 'summer4', 'summer5'); // Array of required coupon codes

    $coupons_found = array_intersect( array_filter( array_map( 'sanitize_title', $coupon_codes) ), WC()->cart->get_applied_coupons() );

    // Loop through cart items
    foreach(WC()->cart->get_cart() as $item ) {
        // Check cart item for defined product Ids and applied coupon
        if( in_array( $item['product_id'], $targeted_ids ) && empty($coupons_found) ) {
            wc_clear_notices(); // Clear all other notices

            // Avoid checkout displaying an error notice
            wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $item['data']->get_name() ), 'error' );
            break; // stop the loop
        }
    }
}

代码位于活动子主题(或活动主题)的functions.php文件中。测试和工作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66355212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档