1
votes

As Salam o Alikum, I'm trying to hide cash on delivery payment method if the product in cart belongs to NOCOD shipping class. I have created a shipping class and its ID is 723, I tried to get help from everywhere on the web but unable to figure out that where I'm doing wrong.

Based on web surfing, I have written code and added it to theme functions.php.

Here is the code snippet.

    //disabling COD if shipping class is NOCOD.

    add_filter('woocommerce_available_payment_gateways', 'hide_cod_if_shipping_class_is_nocod', 10, 2);
    //fuction
    function hide_cod_if_shipping_class_is_nocod( $available_gateways ) {

    $shipping_class_target_id = 723; // shipping class ID 
    $in_cart = false;

    // Not in backend (admin)
    if( is_admin() ) {
    return $available_gateways;
    }

    else{

    foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
    if ( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target_id ) {
    $in_cart = true;
    break;
      } 
     }
    }

    // Remove Cash on delivery (cod) payment gateway for products belongs to NOCOD shipping class
    if($in_cart){
    unset($available_gateways['cod']); 
    } 
    // unset 'cod'
    return $available_gateways;
    }

But it's not working and not hiding Cash on Delivery on the checkout page. Any help, suggestion or tip will be greatly appreciated, Thanks. :)

1

1 Answers

1
votes
add_filter( 'woocommerce_available_payment_gateways', 'hide_cod_if_shipping_class_is_nocod', 10, 2 );


function hide_cod_if_shipping_class_is_nocod( $available_gateways ) {

    $shipping_class_target_id    = 21; // shipping class ID 
    $in_cart                     = false;

    // Not in backend (admin)
    if ( is_admin() ) {
        return $available_gateways;
    } else {

        foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
            if ( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target_id ) {
                unset( $available_gateways[ 'cod' ] );
                break;
            }
        }
    }

    return $available_gateways;
}

Tested ok with shipping class