Skip to content
Advertisement

WooCommerce get_cart() on null

Before I updated to WC at 4.3.1 ,I had this code and it worked well

 add_action( 'rest_api_init', function () {
                    register_rest_route( 'px-module-woocommerce', '/px/cart', array(
                            'methods' => 'POST',
                            'callback' => array($this,'ajax_add_to_cart'),
                    ));
});
public function ajax_add_to_cart() {
       $items = WC()->cart->get_cart();
}

now, WC()->cart->get_cart() still return

Call to a member function get_cart() on null

I also tried the global value $woocommerce. But, the result is still the same. Have you any solution? Thanks.

Advertisement

Answer

I solved including the functions which are loaded only on the front-end.

public function ajax_add_to_cart() {
            include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
            include_once WC_ABSPATH . 'includes/class-wc-cart.php';

            if ( is_null( WC()->cart ) ) {
                wc_load_cart();
            }

           $items = WC()->cart->get_cart();
}

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement