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

Commit 09ffdff

Browse files
authored
Introduce woocommerce_store_api_add_to_cart_data (#7252)
1 parent 93c80e9 commit 09ffdff

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

src/StoreApi/Routes/V1/CartAddItem.php

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -89,15 +89,34 @@ protected function get_route_post_response( \WP_REST_Request $request ) {
8989
throw new RouteException( 'woocommerce_rest_cart_item_exists', __( 'Cannot create an existing cart item.', 'woo-gutenberg-products-block' ), 400 );
9090
}
9191

92-
$cart = $this->cart_controller->get_cart_instance();
93-
$result = $this->cart_controller->add_to_cart(
94-
[
95-
'id' => $request['id'],
96-
'quantity' => $request['quantity'],
97-
'variation' => $request['variation'],
98-
]
92+
$cart = $this->cart_controller->get_cart_instance();
93+
94+
/**
95+
* Filters cart item data sent via the API before it is passed to the cart controller.
96+
*
97+
* This hook filters cart items. It allows the request data to be changed, for example, quantity, or
98+
* supplemental cart item data, before it is passed into CartController::add_to_cart and stored to session.
99+
*
100+
* CartController::add_to_cart only expects the keys id, quantity, variation, and cart_item_data, so other values
101+
* may be ignored. CartController::add_to_cart (and core) do already have a filter hook called
102+
* woocommerce_add_cart_item, but this does not have access to the original Store API request like this hook does.
103+
*
104+
* @param array $customer_data An array of customer (user) data.
105+
* @return array
106+
*/
107+
$add_to_cart_data = apply_filters(
108+
'woocommerce_store_api_add_to_cart_data',
109+
array(
110+
'id' => $request['id'],
111+
'quantity' => $request['quantity'],
112+
'variation' => $request['variation'],
113+
'cart_item_data' => [],
114+
),
115+
$request
99116
);
100117

118+
$this->cart_controller->add_to_cart( $add_to_cart_data );
119+
101120
$response = rest_ensure_response( $this->schema->get_item_response( $cart ) );
102121
$response->set_status( 201 );
103122
return $response;

src/StoreApi/Utilities/CartController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public function load_cart() {
4242
* @throws RouteException Exception if invalid data is detected.
4343
*
4444
* @param array $request Add to cart request params.
45-
* @return string|Error
45+
* @return string
4646
*/
4747
public function add_to_cart( $request ) {
4848
$cart = $this->get_cart_instance();

0 commit comments

Comments
 (0)