Search code examples
phpwoocommercepaymenthook-woocommercecheckout

Hiding COD if subtotal is under a certain amount in WooCommerce, "subtotal" property issue


I am trying to disable/remove the cash on delivery option provided by WooCommerce when an order is under $10

the script I am using is working and in fact it is hiding the option from the checkout page but I am getting errors as such:

[STDERR] PHP Warning: Attempt to read property "subtotal" on null in

add_filter( 'woocommerce_available_payment_gateways', 'ts_disable_cod' );
function ts_disable_cod( $available_gateways ) {
    $minimum = 11;
    if ( WC()->cart->subtotal < $minimum ) {
        unset( $available_gateways['cod'] );
    }
    return $available_gateways;
}

I have tried using WC()->cart->get_cart_subtotal(), but again I see a different set of errors.
How to avoid warning and errors, from my prodided code?


Solution

  • You need to target exclusively checkout page, to avoid warnings or errors. Try the following:

    add_filter( 'woocommerce_available_payment_gateways', 'ts_disable_cod' );
    function ts_disable_cod( $available_gateways ) {
        // Target Checkout to avoid warnings or errors
        if( is_checkout() && ! is_wc_endpoint_url() && WC()->cart ) {
            if ( WC()->cart->subtotal <= 10 ) {
                unset( $available_gateways['cod'] );
            }
        }
        return $available_gateways;
    }
    

    It should work without issues.

    Explanation:

    The cart object is not defined in some cases: In the backend and in "pay-order" endpoint, where the hook woocommerce_available_payment_gateways is also triggered, then WC()->cart->subtotal will logically throw a warning notice 'Attempt to read property "subtotal" on null'.

    Note related to cart subtotal:

    • WC()->cart->subtotal is the cart items subtotal amount including taxes,
    • WC()->cart->get_subtotal() is the cart items subtotal amount excluding taxes.