skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. $WC_Cart = new WC_Cart();
    $total_weight  = $WC_Cart->get_cart_contents_weight();
    

    Try getting the weight like this.

    Login or Signup to reply.
  3. 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.

    add_filter( 'woocommerce_available_payment_gateways', 'hide_payment_gateways_based_on_weight', 10, 1 );
    function hide_payment_gateways_based_on_weight( $available_gateways ) {
        // Check if it's the cart page or the checkout.
        if ( is_cart() || is_checkout() ) {
            $total_weight = WC()->cart->get_cart_contents_weight();
            if ( 2000 >= $total_weight && isset( $available_gateways['cod'] ) ) {
                unset( $available_gateways['cod'] ); // unset 'cod'.
            }
        }
        return $available_gateways;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search