Search code examples
phpwordpresswoocommerceunsetpayment-method

Hide specific payment method based on total weight in Woocommerce


In woocommerce I would like to hide a "Cash on delivery" payment method for a specific total weight.

For example if cart total weight is up to 15 kilos, "Cash on delivery" payment method on checkout.

Any help is appreciated.


Solution

  • The following simple code will hide "COD" payment method if cart total weight is up to 15 Kg.
    I assume that the weight unit set in Woocommerce is Kg (kilos).

    The code:

    add_filter( 'woocommerce_available_payment_gateways', 'hide_payment_gateways_based_on_weight', 11, 1 );
    function hide_payment_gateways_based_on_weight( $available_gateways ) {
        if ( is_admin() ) return $available_gateways; // Only on frontend
    
        $total_weight = WC()->cart->get_cart_contents_weight();
    
        if( $total_weight >= 15 && isset($available_gateways['cod']) )
            unset($available_gateways['cod']); // unset 'cod'
    
        return $available_gateways;
    }
    

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