Disable WooCommerce Payment Type based on Category
Use Case Scenario:
A WooCommerce Shop has two payment option, Check and COD. Without using a plugin, we will create a custom code to disable COD Payment type for products under Wholesale category.
Copy the code below and paste it in functions.php
//Disable payment type by category
add_filter( 'woocommerce_available_payment_gateways', 'wehelpcode_disable_by_category' );
function wehelpcode_disable_by_category( $available_gateways ) {
if ( is_admin() ) return $available_gateways;
if ( ! is_checkout() ) return $available_gateways;
$unset = false;
$category_id = 22;
foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
$terms = get_the_terms( $values['product_id'], 'product_cat' );
foreach ( $terms as $term ) {
if ( $term->term_id == $category_id ) {
$unset = true;
break;
}
}
}
if ( $unset == true ) unset( $available_gateways['cod'] );
return $available_gateways;
}