Hide COD payment method based on shipping class in WooCommerce cart

江枫思渺然 提交于 2021-01-28 19:43:02

问题


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:


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



来源:https://stackoverflow.com/questions/61641249/hide-cod-payment-method-based-on-shipping-class-in-woocommerce-cart

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