My client wanted to conditionally show a Woocommerce payment gateway if all the products in the cart met specific criteria. I had to iterate through the cart contents and examine the specific post meta for each item. Then determine whether to remove the gateway from the allowed gateways queue.
add_filter('woocommerce_available_payment_gateways','tower_payment_gateways');
function tower_payment_gateways($gateways){
// var_dump($gateways);
$target_index = 'my_target_index';
if (isset($gateways[$target_index]) && !is_null( WC()->cart )){
$items = WC()->cart->cart_contents;
if (!empty($items)){
$allow = true;
foreach ($items as $item){
// the next line is whatever condition you want to impose
if (1 != get_post_meta($item['product_id'], 'my_meta_key', true)) {
$allow = false;
break;
}
}
if (!$allow)
unset($gateways[$target_index]);
}
}
return $gateways;
}
To find your target index, you can uncomment the var_dump line while testing and find your index in the array.
