In my WooCommerce store I want to restrict and show payment gateway(cheque) only if the product has particular product category with the category ID "266". Now I have this snippet but it does the opposite – it disabled the gateway on the checkout for particular product category:
add_filter( 'woocommerce_available_payment_gateways', 'bbloomer_unset_gateway_by_category' );
function bbloomer_unset_gateway_by_category( $available_gateways ) {
if ( is_admin() ) return $available_gateways;
if ( ! is_checkout() ) return $available_gateways;
$unset = false;
$category_ids = array( 8, 37 );
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['cheque'] );
return $available_gateways;
}
2
Answers
can you change your condition in your code
Using
has_term()
WordPress conditional function that will simplify the code making it more effective, this way:Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Handling product tags instead
Targeting parent product category too
If you need to target the parent product categories too, you will have to use this instead:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.