I’m trying to deactivate PayPal for all subcategories by a given category slug for WooCommerce. Currently my following code just deactivates the payment method for one category. Is it possible to deactivate for all subcategories?
<?php
/**
* Disable payment gateway based on category.
*/
function ace_disable_payment_gateway_category( $gateways ) {
// Categories that'll disable the payment gateway
$category_slugs = array( 'tobacco' );
$category_ids = get_terms( array( 'taxonomy' => 'product_cat', 'slug' => $category_slugs, 'fields' => 'ids' ) );
// Check each cart item for given category
foreach ( WC()->cart->get_cart() as $item ) {
$product = $item['data'];
if ( $product && array_intersect( $category_ids, $product->get_category_ids() ) ) {
unset( $gateways['ppec_paypal'] );
break;
}
}
return $gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'ace_disable_payment_gateway_category' );
2
Answers
For others with the same issue. @LoicTheAztec code was extended by a code part to check if the single product site is a part of the category too:
Update 2
To disable specific payment gateway for a subcategory of a top product category, use the following:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.