A client recently asked me to create a custom payment gateway for WooCommerce Subscriptions, but disable it for regular products.
While I had left out ‘products’ from the WC_Payment_Gateway
supports
property, the payment method would still show up on checkout, even if the shopping cart contained nothing but regular products.
I thus had to actively remove it from the available payment methods. Thanks to the woocommerce_available_payment_gateways
filter hook, though, doing so is easy enough:
add_filter( 'woocommerce_available_payment_gateways', function( $gateways ) {
// If the cart does not contain a subscription.
if ( ! WC_Subscriptions_Cart::cart_contains_subscription() ) {
// Remove the payment gateway.
unset( $gateways['my_payment_gateway'] );
}
return $gateways;
} );
Note that (1) I’m using a closure rather than a named callback function, and (2) you may want to verify the existence of WC_Subscriptions_Cart::cart_contains_subscription()
.
Also, this trick doesn’t just work for subscription products. You could just as easily disable (or enable) payment methods for a certain product category or shipping method.