如果购物车中的某些产品没有应用优惠券,则防止结帐

时间:2020-10-26 11:41:11

标签: wordpress woocommerce product checkout coupon

我正在WooCommerce网站上工作,我试图限制仅在应用了优惠券的情况下才能购买产品,因此,在未添加优惠券代码的情况下不应对其进行处理。

用户必须输入优惠券代码才能订购该特定产品(不适用于所有其他产品)。

我们不需要它定位到特定的优惠券以允许结帐,我们需要它要求任何优惠券,因为对于此特定产品,我们有大约150多种优惠券。

基于Allow specific products to be purchase only if a coupon is applied in Woocommerce代码线程:

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
    $targeted_ids   = array(37); // The targeted product ids (in this array)
    $coupon_code    = 'summer2'; // 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
        }
    }
}

处理方法:如果购物车中的某些产品没有应用优惠券,则可以防止结帐。

1 个答案:

答案 0 :(得分:1)

这是删除或调整一些条件的问题。例如,检查优惠券是否已应用

  • empty-确定变量是否为空

所以您得到:

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

    // Get applied coupons
    $coupon_applieds = WC()->cart->get_applied_coupons();
    
    // Empty coupon applieds
    if ( empty ( $coupon_applieds ) ) {

        // Loop through cart items
        foreach( WC()->cart->get_cart() as $cart_item ) {
            // Check cart item for defined product Ids
            if ( in_array( $cart_item['product_id'], $targeted_ids )  ) {
                // Clear all other notices          
                wc_clear_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' );
                
                // Optional: remove proceed to checkout button
                remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
                
                // Break loop
                break;
            }
        }
    }
}   
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );