How to disable Cash on Delivery on some specific products in Woocommerce

前端 未结 2 1846
时光取名叫无心
时光取名叫无心 2021-01-07 15:42

I want to disable Cash on Delivery(COD) for some products on my online shopping site.

Is it Possible?

2条回答
  •  不知归路
    2021-01-07 16:10

    Compatible with woocommerce version 3+

    Based on "Disable all payments gateway if there's specifics products in the Cart".

    The code:

    add_filter( 'woocommerce_available_payment_gateways', 'conditionally_disable_cod_payment_method', 10, 1);
    function conditionally_disable_cod_payment_method( $available_gateways ){
        // Not in backend (admin)
        if( is_admin() ) 
            return $available_gateways;
    
        // HERE define your Products IDs
        $products_ids = array(37,40,53);
    
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ){
            // Compatibility with WC 3+
            $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
            if (in_array( $cart_item['product_id'], $products_ids ) ){
                unset($available_gateways['cod']);
                break; // As "COD" is removed we stop the loop
            }
        }
        return $available_gateways;
    }
    

    Code goes in functions.php file of your active child theme (or active theme).

    Tested and works

提交回复
热议问题