In my functions.php I have some code inside a function that has a if (! is_admin) condition around it. For some reason the code inside this condition is running when I edit a page in the admin. Its throwing an error which results in the page not saving.
Here is a sample of the code setup.
function conditional_payment_gateways($available_gateways){
if (!is_admin()){
$payment_type_ins = false;
$payment_type_both = false;
foreach (WC()->cart->get_cart() as $cart_item){
$payment_type = $cart_item['variation']['attribute_pa_payment-type'];
$product_type = get_post_meta($cart_item['product_id'], 'type', true );
if ($payment_type == 'pay-with-insurance' && $product_type != 'Both'){
$payment_type_ins = true;
}
if ($product_type == 'Both'){
$payment_type_both = true;
}
}
if($payment_type_ins){
unset($available_gateways['authorize_net_cim_credit_card']);
} else if ($payment_type_ins == false && $payment_type_both == false){
unset($available_gateways['cod']);
}
return $available_gateways;
}
}
add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
Here is the error it causes when it runs in the editor.
PHP Fatal error: Uncaught Error: Call to a member function get_cart()
Is there a better way to do this?
Edit: Added the full code along with the error it causing when it runs in the editor
Edit #2:
OK, So I figured out a solution for my particular problem.
Instead of using !is_admin() I can use the is_cart() & is_checkout() conditionals.
function conditional_payment_gateways($available_gateways){
if (is_cart() || is_checkout()){
// Code here won't fire in the admin area
}
}
add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
But, I think the larger question still remains. If is_admin() is no longer reliable in the block editor, what should we use?
As Pat J pointed out in a answer below, this is supposed to be a work around. But it didn't work for me.
woocommerce_available_payment_gateways
hook ran in the editor? That's a bit of a red flag. What code is running and what impact is it having?