@@ -89,15 +89,34 @@ protected function get_route_post_response( \WP_REST_Request $request ) {
89
89
throw new RouteException ( 'woocommerce_rest_cart_item_exists ' , __ ( 'Cannot create an existing cart item. ' , 'woo-gutenberg-products-block ' ), 400 );
90
90
}
91
91
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
99
116
);
100
117
118
+ $ this ->cart_controller ->add_to_cart ( $ add_to_cart_data );
119
+
101
120
$ response = rest_ensure_response ( $ this ->schema ->get_item_response ( $ cart ) );
102
121
$ response ->set_status ( 201 );
103
122
return $ response ;
0 commit comments