I’m using this code on my WordPress website to hide the payment gateway when a particular Product variation is selected. However, as soon as I insert the code, WordPress displays a Critical error from the backend. Kindly help me with how to use this code on my website?
Product attribute: Personalization Required
Variables: Yes| No
I want to achieve if someone selects a ‘Yes’ variation then COD options get disabled on the checkout page. Alternatively, if they select ‘No’ then only the cod option is available.
Product Page URL: https://savvyandgroovy.com/product/prashant/
This is what I am currently using:
add_filter(‘woocommerce_available_payment_gateways’, ‘conditional_payment_gateways’, 10, 1);
function conditional_payment_gateways($available_gateways)
{
$in_cart=false;
foreach(WC()->cart->get_cart_contents() as $key=>$values)
{
// See if there is an attribute called ‘pa_size’ in the cart
// Replace with whatever attribute you want
if(array_key_exists(‘personalization-required’, (array)$values[‘data’]->get_attributes()))
{
foreach($values[‘data’]->get_attributes() as $attribute=>$variation) ;
// Replace ‘small’ with your value.
if($variation==‘Yes’) $in_cart=true; //edited
}
}
if($in_cart)
unset($available_gateways[‘cod’]); // unset ‘cod’
return $available_gateways;
}
2
Answers
Your code is working properly but it is giving error because of quotes which you are using. I have updated it as bellow:
I want to achieve if someone selects a ‘NO’ variation then cod options get disabled on the checkout page Alternatively, if they select ‘YES’ then only the cod option is available.
This will not work reverse in your code because you have written
if ($variation == ‘Yes’) $in_cart = true; //edited
so you need to update it also. So that also I have updated in above code.The code above is not quite full since the OP wants to hide payment gateways in both scenarios so i just tweak the 1st answer a bit.
Keep in mind that if you add both variations in cart youll be left with no payment method.