Skip to content

Fatal: Call to get_cart() on null in Cart.php — check_cart_items() and 2 other methods do not null-check WC()->cart #286

Description

@officialsyntec

Summary

Several methods in includes/Cart.php call WC()->cart->get_cart() without checking whether WC()->cart is null. When the woocommerce_check_cart_items action (or add-to-cart validation) fires in a request context where WooCommerce has not initialised the cart, the plugin throws an uncaught fatal and takes down the page for the visitor.

Error

PHP Fatal error: Uncaught Error: Call to a member function get_cart() on null
in .../plugins/wc-min-max-quantities/includes/Cart.php:328
#0 wp-includes/class-wp-hook.php(341): WooCommerceMinMaxQuantities\Cart::check_cart_items()
...
plugin.php(522): do_action('woocommerce_check_cart_items')

Affected code (current master, 2.3.0)

check_cart_items(), add_to_cart_validation() and set_cart_quantity() each iterate the cart with no guard against a null cart object:

foreach ( WC()->cart->get_cart() as $item ) { ... }

Why WC()->cart can be null

WC()->cart is only initialised in front-end cart contexts; it is null in REST API and other optimised/early loads — long-standing WooCommerce behaviour (see woocommerce/woocommerce#23792, #23758, #27157). Any code that triggers woocommerce_check_cart_items outside a normal cart context — for example a floating-cart plugin rendering on wp_footer — reliably hits this and fatals.

Steps to reproduce

WC()->cart = null;
do_action( 'woocommerce_check_cart_items' ); // -> Fatal in check_cart_items()

Environment

  • Min Max Quantities 2.3.0
  • WooCommerce 10.9.1
  • WordPress 6.9
  • PHP 8.3

Suggested fix

Add a null guard at the top of each method that dereferences WC()->cart:

if ( is_null( WC()->cart ) ) {
    return; // for the add_to_cart_validation filter: `return $pass;`
}

Happy to open a PR with the guards if that helps.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions