繁体   English   中英

根据 WooCommerce 购物车中的商品数量和产品类别禁用支付网关

[英]Disable payment gateway based on number of items and product category in WooCommerce cart

我正在使用以下代码,它允许我在购物车中设置最少数量的产品以继续付款

// Allow order only product quantity increment

function s5_unsetting_payment_gateway( $available_gateways ) {
  if ( ! is_admin() ) {
    $cart_quantity = WC()->cart->get_cart_contents_count();

    if ( ( $cart_quantity % 6 ) !== 0 ) {
        unset($available_gateways['cod']);
        unset($available_gateways['bacs']);
    }
  }

  return $available_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 's5_unsetting_payment_gateway', 10, 1 );

是否有一些选项可以排除某些特定类别?

例如:

我需要为6件商品设置一个订单的最小数量(适用于所有类别)。

但是,对于一类产品(ID 2),我希望如果购物篮中只有该类别的商品,则将订单的最小数量设置为 3 件。

有什么建议吗?

这个答案包含:

  • 如果产品不属于特定类别,则最小数量为 6
  • 如果所有产品都属于该类别,则最小数量将为 3

所以你得到:

function filter_woocommerce_available_payment_gateways( $payment_gateways ) {
    // Not on admin
    if ( is_admin() ) return $payment_gateways;

    // Term_id
    $cat_id = 2;
    
    // Default
    $minimum_quantity = 3;
    
    // WC Cart
    if ( WC()->cart ) {
        // Get total items in cart, counts number of products and quantity per product
        $cart_quantity = WC()->cart->get_cart_contents_count();
        
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            // When a product does not belong to the specific category, the if condition will apply
            if ( ! has_term( $cat_id, 'product_cat', $cart_item['product_id'] ) ) {
                $minimum_quantity = 6;
                break;
            }
        }
    
        // Condition modulo
        if ( ( $cart_quantity % $minimum_quantity ) !== 0 ) {
            // Bacs
            if ( isset( $payment_gateways['bacs'] ) ) {
                unset( $payment_gateways['bacs'] );
            }
            
            // Cod
            if ( isset( $payment_gateways['cod'] ) ) {
                unset( $payment_gateways['cod'] );
            }  
        }
    }
    
    return $payment_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'filter_woocommerce_available_payment_gateways', 10, 1 );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM