Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Introduce woocommerce_store_api_add_to_cart_data (#7252)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikejolley authored and sunyatasattva committed Oct 22, 2022
1 parent d8e2029 commit 759c1be
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
33 changes: 26 additions & 7 deletions src/StoreApi/Routes/V1/CartAddItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,34 @@ protected function get_route_post_response( \WP_REST_Request $request ) {
throw new RouteException( 'woocommerce_rest_cart_item_exists', __( 'Cannot create an existing cart item.', 'woo-gutenberg-products-block' ), 400 );
}

$cart = $this->cart_controller->get_cart_instance();
$result = $this->cart_controller->add_to_cart(
[
'id' => $request['id'],
'quantity' => $request['quantity'],
'variation' => $request['variation'],
]
$cart = $this->cart_controller->get_cart_instance();

/**
* Filters cart item data sent via the API before it is passed to the cart controller.
*
* This hook filters cart items. It allows the request data to be changed, for example, quantity, or
* supplemental cart item data, before it is passed into CartController::add_to_cart and stored to session.
*
* CartController::add_to_cart only expects the keys id, quantity, variation, and cart_item_data, so other values
* may be ignored. CartController::add_to_cart (and core) do already have a filter hook called
* woocommerce_add_cart_item, but this does not have access to the original Store API request like this hook does.
*
* @param array $customer_data An array of customer (user) data.
* @return array
*/
$add_to_cart_data = apply_filters(
'woocommerce_store_api_add_to_cart_data',
array(
'id' => $request['id'],
'quantity' => $request['quantity'],
'variation' => $request['variation'],
'cart_item_data' => [],
),
$request
);

$this->cart_controller->add_to_cart( $add_to_cart_data );

$response = rest_ensure_response( $this->schema->get_item_response( $cart ) );
$response->set_status( 201 );
return $response;
Expand Down
2 changes: 1 addition & 1 deletion src/StoreApi/Utilities/CartController.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function load_cart() {
* @throws RouteException Exception if invalid data is detected.
*
* @param array $request Add to cart request params.
* @return string|Error
* @return string
*/
public function add_to_cart( $request ) {
$cart = $this->get_cart_instance();
Expand Down

0 comments on commit 759c1be

Please sign in to comment.