【问题标题】:Woocommerce: Mandatory coupon for specific productsWoocommerce:特定产品的强制性优惠券
【发布时间】:2021-02-24 16:45:35
【问题描述】:

基于Make coupon field mandatory for a product category in WooCommerce 的回答,我正在尝试在woocommerce 中为特定产品实施强制优惠券。

这是我的代码尝试:

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,summer 4和summer5,否则无法结帐。我希望客户可以使用 targets_id 数组中列出的任何产品的任何优惠券进行结帐。

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

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

提前谢谢你

【问题讨论】:

    标签: php wordpress woocommerce product coupon


    【解决方案1】:

    您的代码中有一些错误,请改用以下代码:

    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 文件中。经过测试并且可以工作。

    【讨论】:

    • 效果很好!非常感谢@LoicTheAztec
    猜你喜欢
    • 2017-06-06
    • 2021-06-10
    • 2021-04-13
    • 1970-01-01
    • 2021-11-06
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多