Disable Payment Method for Specific Category in Woocommerce

I need to disable payment for certain categories on my woocommerce website. so, A simple filter to disable a user-specified payment gateway when a product with a user-specified category is added to the shopping cart. Add code to your theme’s theme’s functions.php file of your active child theme (or theme).

In this code,

category_ids: The ID of the category for which the gateway will be removed. Get the ID by clicking on the category under Products -> Categories and reading the “tag_ID” in the address bar.

i.e. http://localhost/Woocommercedemo/wp-admin/term.php?taxonomy=product_cat&tag_ID=19&post_type=product&wp_http_referer=%2FWoocommercedemo%2Fwp-admin%2Fedit-tags.php%3Ftaxonomy%3Dproduct_cat%26post_type%3Dproduct
=> The tag id is 19

available_gateways: One of the five hardcoded Woocommerce standard types of payment gateways – paypal, cod, bacs, cheque or mijireh_checkout.

add_filter( 'woocommerce_available_payment_gateways', 'wp_unset_gateway_by_category' );
 
function wp_unset_gateway_by_category( $available_gateways ) {
global $woocommerce;
$unset = false;
$category_ids = array( 19, 37 ); // The ID of the category for which the gateway  will be removed.  Get the ID by clicking on the category under Products -> Categories and reading the "tag_ID" in the address bar.
foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
    $terms = get_the_terms( $values['product_id'], 'product_cat' );    
    foreach ( $terms as $term ) {        
        if ( in_array( $term->term_id, $category_ids ) ) {
            $unset = true;
            break;
        }
    }
}
    if ( $unset == true ) unset( $available_gateways['cod'] ); // One of the five hardcoded Woocommerce standard types of payment gateways - paypal, cod, bacs, cheque or mijireh_checkout
    return $available_gateways;
}

Leave a Comment

Scroll to Top