如果购物车中有特定产品,则禁用所有支付网关

Disable all payments gateway if there's specifics products in the Cart

我想在特殊情况下禁用所有支付网关:
我有 2 种特殊产品,我不想在结账时与任何其他产品组合使用。

假设我的 "special" 产品 ID 是 496484。其他都是"normal"产品。

  1. 如果这些 "special" 产品之一在购物车中,我想禁用 "paypal" 例如。

  2. 如果客户的购物车中同时有一个 "special" 产品和一个 "normal" 产品,我想禁用所有支付网关,所以他不能结账。

这是我的代码:

//disable add to cart if
add_filter( 'woocommerce_available_payment_gateways', 'filter_gateways', 1);

function filter_gateways( $gateways )
{   
    global $woocommerce;

    foreach ($woocommerce->cart->cart_contents as $key => $values ) {   
        // store product IDs in array   
        $nonPPproducts = array(496,484);        

        if (in_array( $values['product_id'], $nonPPproducts ) ) {
            unset($gateways['cod'], $gateways['bacs'], $gateways['cheque'], $gateways['stripe']);
        } elseif ( in_array( $values['product_id'], $nonPPproducts ) && in_array( $values['product_id'] ) ) {           
            unset($gateways['under-review'], $gateways['cod'], $gateways['bacs'], $gateways['cheque'], $gateways['stripe']);
        }
    }

    return $gateways;   
}

但我不明白为什么只有第一个 if 语句有效……换句话说,无论在什么情况下,除了 under-review 支付网关外,所有支付网关都被禁用.

我做错了什么?
我怎样才能做到这一点?

谢谢

Updated for WooCommerce 3+

首先,我认为您的代码中的 in_array( $values['product_id'] ) 无法正常工作,因此您的 else 语句永远不会是 "true"。然后,由于客户的购物车中可以有很多商品,具体取决于客户的连续选择,您的代码将有许多冗余 未设置网关

这是您重新访问的代码(您需要在每条语句中放入未设置网关的愿望):

add_filter( 'woocommerce_available_payment_gateways', 'filter_gateways', 1);
function filter_gateways( $gateways ){
    // Not in backend (admin)
    if( is_admin() ) 
        return $gateways;

    // Storing special product IDs in an array
    $non_pp_products = array( 496, 484 );

    // Needed variables
    $is_non_prod = false;
    $is_prod = false;
    $count = 0;

    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // count number of items if needed (optional) 
        $count++;
        $product = $cart_item['data'];
        if( ! empty($product) ){
            $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
            if ( in_array( $product_id, $non_pp_products ) && ! $is_non_prod ) 
                $is_non_prod = true;

            if ( !in_array( $product_id, $non_pp_products ) && !$is_prod )
                $is_prod = true;

        }
    }
    if ( $is_non_prod && ! $is_prod ) // only special products 
    {
        // unset only paypal;
        unset( $gateways['paypal'] );
    } 
    elseif ( $is_non_prod && $is_prod ) // special and normal products mixed
    {
        // unset ALL GATEWAYS
        unset( $gateways['cod'], 
               $gateways['bacs'], 
               $gateways['cheque'], 
               $gateways['paypal'], 
               $gateways['stripe'], 
               $gateways['under-review'] );
    }
    elseif ( ! $is_non_prod && $is_prod ) // only normal products (optional)
    {
        // (unset something if needed)
    }
    return $gateways; 
}

自然地,此代码会出现在您的活动子主题或主题的 functions.php 文件中。