admin管理员组文章数量:1122832
I have spent almost two days on this problem.
I want to write a dedicated REST API for WooCommerce that removes a product from the user's shopping cart.
I delete the product, but unfortunately the new session is not saved I tested many models of the set() method, but none of them saved the session.
Please guide me if you know what is the problem with my code and why the new session is not saved thank you.
// Hook into REST API initialization
add_action('rest_api_init', 'register_custom_rest_endpoint');
// Register custom REST API endpoint
function register_custom_rest_endpoint()
{
register_rest_route('custom/v1', '/cart/remove', array(
'methods' => 'DELETE',
'callback' => 'handle_remove_product_from_cart',
));
}
function handle_remove_product_from_cart($data)
{
$user_email = sanitize_email($data['email']);
$product_id = intval($data['product_id']);
$user = get_user_by('email', $user_email);
if (!$user) {
return new WP_REST_Response(array('error' => 'User not found.'), 404);
}
$session_handler = new WC_Session_Handler();
$session = $session_handler->get_session($user->ID);
$cart_items = maybe_unserialize($session['cart']);
if (empty($cart_items)) {
return new WP_REST_Response(array('message' => 'Cart is empty.'), 200);
}
foreach ($cart_items as $cart_item_key => $cart_item) {
if ($cart_item['product_id'] === $product_id) {
// Remove the product from the cart
unset($cart_items[$cart_item_key]);
break; // Stop searching after finding the product
}
}
// remove product from old session
$session['cart'] = serialize($cart_items);
// new session not saving
$session_handler->set($session['cart'], $session);// for test
$session_handler->set($user->ID, $session['cart']); // for test
$session_handler->set($user->ID, serialize($cart_items));// for test
$session_handler->set(serialize($cart_items), $session);// for test
$session_handler->set(serialize($cart_items), $user->ID);// for test
$session_handler->save_data( ); // not set and not saving new session
return new WP_REST_Response(array('message' => 'Product removed from cart.'), 200);
}
I spent almost two days trying to create a new cart session using the set() and save() methods, but there was no result. I just want the new session to be saved for the user after the product is removed from the user's shopping cart.
本文标签:
版权声明:本文标题:not saving the WC_Session_Handler session and removing the product from the cart session in WooCommerce's custom rest ap 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736310360a1934348.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论