Reputation: 127
I have been trying to build a custom api endpoint to add to cart. My local is working fine and adding the product to the cart easily. I made the code live and getting an error like:
Call to a member function generate_cart_id() on null
Here is the code I have written.
add_action('rest_api_init', function () {
register_rest_route( 'product/v1', 'add_to_cart',array(
'methods' => 'POST',
'callback' => 'wplms_add_to_cart'
));
});
function wplms_add_to_cart($request) {
$product_id = $request['product_id'];
$product_cart_id = WC()->cart->generate_cart_id($product_id);
if( ! WC()->cart->find_product_in_cart( $product_cart_id ) ){
// The product ID is NOT in the cart, let's add it then!
$added = $cart->add_to_cart( $product_id);
}
$response = new WP_REST_Response(var_dump($added));
$response->set_status(200);
return $response;
}
Upvotes: 1
Views: 1954
Reputation: 127
The way I resolved it.
if ( defined( 'WC_ABSPATH' ) ) {
// WC 3.6+ - Cart and other frontend functions are not included for REST requests.
include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
include_once WC_ABSPATH . 'includes/wc-notice-functions.php';
include_once WC_ABSPATH . 'includes/wc-template-hooks.php';
}
if ( null === WC()->session ) {
$session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' );
WC()->session = new $session_class();
WC()->session->init();
}
if ( null === WC()->customer ) {
WC()->customer = new WC_Customer( get_current_user_id(), true );
}
if ( null === WC()->cart ) {
WC()->cart = new WC_Cart();
// We need to force a refresh of the cart contents from session here (cart contents are normally refreshed on wp_loaded, which has already happened by this point).
$cart = WC()->cart->get_cart();
$product_cart_id = WC()->cart->generate_cart_id($request['product_id']);
$cart_item_key = WC()->cart->find_product_in_cart($product_cart_id);
if (!$cart_item_key) {
$add = WC()->cart->add_to_cart( $product_id = $request['product_id'], $quantity = 1, $variation_id = 0, $variation = array(), $cart_item_data = array() );
} else {
$add = false;
}
}
Upvotes: 2