7

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.

TimBrownlaw
  • 5,457
  • 3
  • 24
  • 28
riccardo tocco
  • 167
  • 1
  • 6
  • I dont have much experience in this area but would this reference assist you: https://docs.woocommerce.com/wc-apidocs/class-WC_Cart.html – Aliqua Jul 25 '20 at 11:00
  • Thank you for your reply. Yes that documentation is very useful, but describe only the `WC_Cart` class and is used through a Singleton in the main class WooCommerce. `WC()->cart` = `WC_Cart`. – riccardo tocco Jul 25 '20 at 13:00

1 Answers1

4

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();
}
riccardo tocco
  • 167
  • 1
  • 6