Home » WordPress » Disable Payment method for specific category using PHP code

Disable Payment method for specific category using PHP code

in this article we will learn how to disable payment method in  WooCommerce for specific category using PHP code. If you are not familiar with PHP then there are few plugins do the same thing. we will discuss about it next article.

PHP code goes to function.php

/**
 * @snippet       Disable Payment Method for Specific Category
 * @how-to
 * @compatible    WooCommerce
 */

add_filter( 'woocommerce_available_payment_gateways', 'wpdumi_unset_gateway_by_category' );

function wpdumi_unset_gateway_by_category( $available_gateways ) {
    if ( is_admin() ) return $available_gateways;
    if ( ! is_checkout() ) return $available_gateways;
    $unset = false;
    $category_name = 'your_category_slug';
// $amount = floatval( preg_replace( '#[^\d.]#', '', WC()->cart->get_cart_total() ) );

    foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
        $terms = get_the_terms( $values['product_id'], 'event_cat' );
       // var_dump($terms);
        foreach ( $terms as $term ) {
            if ( $term->slug == $category_name ) {
                $unset = true;
                break;
                // here we check if any product price is less than 1000
            } //else if($amount < 1000){
              //  $unset = true;
              //  break;
            // }
        }
    }
    if ( $unset == true ) unset( $available_gateways['bacs'] ); // DISABLE Direct Bank Tranfer
    return $available_gateways;
}

instead of having category slug you can use category id then code will be change as bellow

/**
 * @snippet       Disable Payment Method for Specific Category
 * @how-to
 * @compatible    WooCommerce
 */

add_filter( 'woocommerce_available_payment_gateways', 'wpdumi_unset_gateway_by_category' );

function wpdumi_unset_gateway_by_category( $available_gateways ) {
    if ( is_admin() ) return $available_gateways;
    if ( ! is_checkout() ) return $available_gateways;
    $unset = false;
    $category_id = 3; // target category id
    
    foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
        $terms = get_the_terms( $values['product_id'], 'event_cat' );
        foreach ( $terms as $term ) {
            if ( $term->term_id == $category_id ) {
                $unset = true;
                break;
            }
        }
    }
    if ( $unset == true ) unset( $available_gateways['bacs'] ); // DISABLE Direct Bank Tranfer
    return $available_gateways;
}
Duminda Wijerathna

An all round web designer building websites Over 18 years. Interested in achieving a suitable placement in the field of IT in a growth oriented organization which offers diverse job responsibilities in order to utilize and improve my skills, Knowledge and experience.

Leave a Comment

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