A have a ton of variable products. I’m using cron to run the script every X minutes for fetching stock level from an external source. If I use wc_get_product_id_by_sku
and update_post_meta
it takes too long so I’m trying to find the way to use a custom prepared query.
If I know product_id
query would be like that:
$conn->prepare( "UPDATE wp_postmeta SET meta_value=? WHERE post_id=? AND meta_key=`_stock`" );
But I only know a product SKU. So how to modify this query to update _stock
based on a product SKU?
post_id | meta_key | meta_value |
---|---|---|
10 | _sku | ABCD |
10 | _stock | 25 |
3
Answers
$wpdb
andJOIN
works too slow, so the fastest way is to use four separate prepared queries:You need first post id then you can update stock value.
First get the post id by sku
we will get product id then just guess
$productValue = 50; then
dear try this code it will work
You can use the following SQL query embedded in a function that will update product stock quantity based on the product SKU (the table
wp_wc_product_meta_lookup
needs also to be updated):Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Related: How can I do an UPDATE statement with JOIN in SQL Server?