wordpress - 使用 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
}
}
关于如何实现这一目标或是否有可能的任何想法?
解决方案
所以我今天才这样做,你确实需要编写一个手动 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);
}
推荐阅读
- godot - 通过 Godot 中的嵌套函数传递变量的正确方法是什么?
- bash - bash脚本未执行
- python - 多服务器套接字条件
- swiftui - SwiftUI SpriteView 问题 - 停止添加节点
- python - 烧瓶网络服务器 | 停止 python 脚本会导致崩溃
- javascript - 从 APII 过滤数据
- laravel - 我在创建 API 以更新 laravel 中的图像时遇到问题
- javascript - 发送大量获取请求的最快方法是什么
- python - 如何在 web2py 数据结构中设置 IS_NOT_EMPTY 和字符串(不包括 0-9)
- javascript - 如何将数据传递给 cron 作业并保留它