I have a shopping cart with retail and wholesale products. Originally, it was only wholesale and we removed the payment gateways altogether and the cart would simply send an email without needing payments.
Now we're needing to enable payment gateways for retail products only. I tried the below and it shows payment gateways for retail and wholesale categories.
Help appreciated.
Original Code
Disable all payment gateways on the checkout page and replace the "Pay" button by "Place order"
add_filter( 'woocommerce_cart_needs_payment', '__return_false' );
New Code
add_filter( 'woocommerce_cart_needs_payment', 'kanna_unset_gateway_by_category', 10, 2 );
function kanna_unset_gateway_by_category( $available_gateways ) {
if ( is_admin() ) return $available_gateways;
if ( ! is_checkout() ) return $available_gateways;
$unset = false;
$category_ids = array( 132, 34, 131, 26, 24, 101, 123 );
foreach ( WC()->cart->get_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['square_credit_card'] );
return $available_gateways;
}
CodePudding user response:
Try this:
add_filter('woocommerce_cart_needs_payment', 'kanna_unset_gateway_by_category', 10, 2);
function kanna_unset_gateway_by_category($available_gateways)
{
if (is_admin()) {
return $available_gateways;
}
if (!is_checkout()) {
return $available_gateways;
}
$enable_payment_gateways = true;
$category_ids = array(132, 34, 131, 26, 24, 101, 123, 181);
foreach (WC()->cart->get_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)) {
$enable_payment_gateways = false;
break;
}
}
}
if ($enable_payment_gateways === false) {
return false;
}
return true;
}