How to create a Woocommerce Rest endpoint to Add all items to cart

Questo articolo รจ stato scritto oltre 1 years, il contenuto potrebbe essere datato.

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'];
        $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.

        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) {
        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.

Liked it? Take a second to support Mte90 on Patreon!
Become a patron at Patreon!

Leave a Reply

Your email address will not be published. Required fields are marked *