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. This approach ensures that the payment gateway restrictions are applied dynamically based on the cart contents.
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
$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 232 not present
break 2;
}
}
}
// If products from target category are in cart, disable all payment methods
if ( $has_category ) {
foreach ( $available_gateways as $gateway_id => $gateway ) {
if ( 'ew_wise' !== $gateway_id ) {
unset( $available_gateways[ $gateway_id ] );
}
}
} else {
// If products from the target category are not in the cart, disable 'ew_wise'
unset( $available_gateways['ew_wise'] );
}
return $available_gateways;
}
Leave a Reply