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

微笑、不失礼 提交于 2019-12-01 13:02:41

Updated for WooCommerce 3+

First I think that in_array( $values['product_id'] ) in your code is not working as a correct condition and so your else statement is never "true". Then as a customer can have many items in his cart, depending on customer successive choices, with your code there will be many redundant gateway unsets

Here it is your code revisited (you will need to put the desire unset gateways in each statement):

add_filter( 'woocommerce_available_payment_gateways', 'filter_gateways', 1);
function filter_gateways( $gateways ){
    // Not on 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; 
}

Naturally this code goes on function.php file of your active child theme or theme.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!