Although the function seems to work perfectly on the front end, on the backend I have :
CRITICAL Uncaught Error: Call to a member function
get_cart_contents_weight() on null in……..
This is the function.
add_filter( 'woocommerce_available_payment_gateways', 'hide_payment_gateways_based_on_weight', 10, 1 );
function hide_payment_gateways_based_on_weight( $available_gateways ) {
if ( is_admin() )
return $available_gateways;
$total_weight = WC()->cart->get_cart_contents_weight();
if ( $total_weight >= 2000 && isset ($available_gateways['cod']) )
unset($available_gateways['cod']); // unset 'cod'
return $available_gateways;
}
3
Answers
The first order problem is that cart in WC()->cart is not defined/null. You should check if that is defined before trying to get the weight. Why cart is null is a second order problem that we can’t really determine with this code snippet. It could be just a normal uninitialized case or some other problem.
Try getting the weight like this.
The reason your function is throwing a critical error on the admin is because there is no cart in the WC Admin. Using
is_admin()
doesn’t work within the WC admin, so your$total_weight
declaration is throwing the error.To ensure you are only showing the gateways on the cart or checkout, use those conditionals.
Also, for whatever it’s worth… WPCS and PHPCS don’t like inline controls. You should wrap your if statements in brackets for cleaner readability.