1

I'd like to update the stock of a product with the Woocommerce API. I managed to do this by querying on the product ID and using the following code:

curl -X PUT \
  https://www.kilikili.be/wp-json/wc/v3/products/10340 \
  -H ...
  -b ...
  -d '{
    "manage_stock": true,
    "stock_quantity": "1"
}'

However, I'd like to do the same now by using the sku.
I tried this:

curl -X PUT \
  'https://www.kilikili.be/wp-json/wc/v3/products?sku=test' \
  -H ...
  -b ...
  -d '{
    "manage_stock": true,
    "stock_quantity": "2"
}'

However, I'm getting the following response:

{
    "code": "rest_no_route",
    "message": "No route was found matching the URL and the request method",
    "data": {
        "status": 404
    }
}

Any idea on how to achieve this or if it is even possible?

Jesse Nickles
  • 1,435
  • 1
  • 17
  • 25
BarrieO
  • 129
  • 2
  • 15
  • Apparently, this can be achieved by creating a custom endpoint, which I’m currently trying using this documentation: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/ – BarrieO Feb 02 '20 at 07:28
  • Hi @BarrieO, did you find a workaround? Any solution that you could share with us? Thanks! – RickON May 11 '20 at 15:20

1 Answers1

0

So I just did this today, you do need to write a manual API. My API below takes a list of products by SKU and QTY and updates all their QTY. Simple amend for you to just do 1 product

//API for product sync//
add_action( 'rest_api_init', 'my_register_prod_sync' );
function my_register_prod_sync(){
      
       register_rest_route(
         'custom', 
         'prodsync',
           array(
               'methods' => 'PUT',
               'callback' => 'prodsync',
               'permission_callback' => 'check_access'
           )
        );

   }

   function prodsync(WP_REST_Request $request) {

    $totalamended = 0;
      //$body = $request->get_body();\
      $intentToPut = $request->get_body();
      $data = json_decode($intentToPut, true);
      foreach($data['products'] as $result) {

        //echo $result['id'], '<br>';
        $stockqty = $result['qty'];
        $sku = $result['sku'];
      global $wpdb;
      $idgrab = $wpdb->get_results("SELECT post_id from wp_25db5fe0d1_postmeta
      where meta_value = $sku");

      if ($idgrab){
        $postidtwo = $idgrab[0]->post_id;
        $updateresults = $wpdb->query("UPDATE wp_25db5fe0d1_postmeta
      SET meta_value = $stockqty 
      WHERE meta_key = '_stock'
      AND post_id = $postidtwo ");

        $totalamended = $totalamended += $updateresults;
      }
    }



      
      


      return rest_ensure_response($totalamended);

   }
user2389087
  • 1,692
  • 3
  • 17
  • 39