Hide a Payment Method for Certain Products
Removes a payment method, for example cash on delivery or buy-now-pay-later, when the cart contains products from categories it should not be used for.
Opens WPIDE on
Code
$wpide_gateway_cat_rules = array( // Gateway ID => category slugs that hide it.
'cod' => array( 'gift-cards', 'digital' ),
);
add_filter( 'woocommerce_available_payment_gateways', function ( $gateways ) use ( $wpide_gateway_cat_rules ) {
if ( ( is_admin() && ! wp_doing_ajax() ) || ! WC()->cart ) {
return $gateways;
}
foreach ( WC()->cart->get_cart() as $item ) {
foreach ( $wpide_gateway_cat_rules as $gateway => $categories ) {
if ( isset( $gateways[ $gateway ] ) && has_term( $categories, 'product_cat', $item['product_id'] ) ) {
unset( $gateways[ $gateway ] );
}
}
}
return $gateways;
} );
Notes
The payment method comes back as soon as those products leave the cart.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.