WooComerce: Restrict payment method by product category

This is a custom filter to restrict certain payment methods on the WooCommerce, considering the product categories.

add_filter('woocommerce_available_payment_gateways','restrict_gateways');

function restrict_gateways($gateways){

    $payment_name = 'your_payment_id';
    $product_category = 'your_category_name';

    global $woocommerce;

    foreach ($woocommerce->cart->cart_contents as $key => $values ) {
        
        $terms = get_the_terms( $values['product_id'], 'product_cat' );
        
        if (! $terms) {
            unset($gateways[$payment_name]);
            break;
        }
        
        foreach ($terms as $term) {
        
            if ( $term->name != $product_category ) {
                unset($gateways[$payment_name]);
                break;
            }
        
            break;
        }
    }

    
    return $gateways;

}
1 reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *