Recently one of my clients asked me to make the following change to a website. For specific products, hide all payment methods except Wise Payments. But at the same time hide the Wise Payments payment method for all other products.
To solve this problem, I added a “Limited” category and added additional code to functions.php.
add_filter( 'woocommerce_available_payment_gateways', 'osw_unset_gateways_by_category' );
/**
* Filter function to unset payment gateways based on product category.
*
* @param array $available_gateways List of available payment gateways.
* @return array Modified list of available payment gateways.
*/
function osw_unset_gateways_by_category( $available_gateways ) {
// If in admin, return original gateways.
if ( is_admin() ) return $available_gateways;
// If not on checkout page, return original gateways.
if ( ! is_checkout() ) return $available_gateways;
$category_id = 232; // ID of the target category (Limited).
$has_category = false; // Assume category not found initially.
// Check if products in cart belong to the specified category.
foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
$terms = get_the_terms( $values['product_id'], 'product_cat' );
foreach ( $terms as $term ) {
if ( $term->term_id == $category_id ) {
$has_category = true; // Category found in cart.
break 2; // Break both loops.
}
}
}
// If category not found, disable the 'wc-wise-gateway' payment method.
if ( ! $has_category ) {
unset( $available_gateways['ew_wise'] );
}
// If products from target category are in cart, disable other payment methods.
if ( $has_category ) {
unset( $available_gateways['eh_paypal_express'] );
unset( $available_gateways['stripe'] );
unset( $available_gateways['klarna_payments_pay_over_time'] );
unset( $available_gateways['klarna_payments_pay_later'] );
unset( $available_gateways['stripe_afterpay'] );
}
return $available_gateways;
}
Leave a Reply