首页 > 解决方案 > 使用 WooCommerce API 根据 SKU 更新产品库存数量?

问题描述

我想使用 Woocommerce API 更新产品的库存。我设法通过查询产品 ID并使用以下代码来做到这一点:

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

但是,我现在想通过使用sku来做同样的事情。
我试过这个:

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

但是,我收到以下回复

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

关于如何实现这一目标或是否有可能的任何想法?

标签: wordpressapirestwoocommercesku

解决方案


所以我今天才这样做,你确实需要编写一个手动 API。我下面的 API 按 SKU 和 QTY 列出了产品列表,并更新了它们的所有数量。简单修改为您只做 1 个产品

//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);

   }

推荐阅读