It will help you to improve your skills or how to understand how to start this journey!
So WordPress REST are very handy, the issues is that they were pushed when they weren’t covering all the features.
The same for Woocommerce that has many of them private or undocumented because they are used in Gutenberg blocks.
There is a endpoint to add a single product to cart but is not very comfortable to use as you can understand.
The only solution is to create a custom endpoint with that code
add_action( 'rest_api_init', function () { register_rest_route( 'yourdomain', 'add-items', array( 'methods' => 'POST', 'args' => array( 'items' => array( 'required' => true, ) ), 'callback' => 'yourdomain_add_items', 'permission_callback' => '__return_true' ) ); } );
With this code we are creating the endpoint with no permission like for users logged.
function yourdomain_add_items( WP_REST_Request $request ) { if ( wp_verify_nonce( $request->get_header( 'X-yourdomain-Nonce' ), 'yourdomain_api' ) ) { $items = $request['items']; wc_load_cart(); $cart = wc()->cart; foreach ($items as &$item) { $cart->add_to_cart( $item['id'] ); } $response = rest_ensure_response( $cart->get_cart() ); $response->set_status( 201 ); } else { $response = rest_ensure_response( 'Wrong nonce' ); $response->set_status( 500 ); } return $response; }
We are not crazy people that don’t want any check, infact we are using a custom Nonce that will be added also with the one to use the REST endpoints (and access to global variables required for Woocommerce).
The code is very simple, checks the nonce and from that parameters add them to the cart and print a complete cart at the end in the request.
jQuery.ajax({ type: 'POST', url: '" . get_site_url() . "/wp-json/yourdomain/add-items', dataType: 'json', headers: { 'X-youtdomain-Nonce': '" . wp_create_nonce( 'yourdomain_api' ) . "', 'X-WP-Nonce': '" . wp_create_nonce( 'wp_rest' ) . "', }, data: { items: items } }).error(function(data) { console.log(data) }).done(function(data){ window.location.href = '" . wc_get_checkout_url() . "'; });
This is an example JS code in jQuery but you can use whatever framework you prefer.
as you can see we are settings 2 different headers, one is our custom and one is the default one for WP endpoints that let us to access to global variables in PHP otherwise we cannot interact with the user sessions for the cart.