I need so help. I'm trying to update the woocommerce product stock quantity programmatically. We have a vendor feed to us through some JSON. I can read the stock from the feed and can pull the data from the post meta correctly. I'm using the latest version of WP and WOO. PHP is 7.2
Below is how I am finding the Product ID from the SKU.
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
This is returning the correct ID and I can use it to see the current metadata that is already there:
$website_stock = get_post_meta($product_id, '_stock', true);
echo "Website Stock - " . $website_stock . "</br>";
$website_stock_status = get_post_meta($product_id, '_stock_status', true);
echo "Website Stock Status - " . $website_stock_status . "</br>";
I then update the stock I am getting from the feed. This can be stock going from zero to x or x to zero and anywhere in between. This is how I am updating the out of stock:
$out_of_stock_staus = 'outofstock';
update_post_meta($product_id, '_stock', 0);
update_post_meta($product_id, '_stock_status', wc_clean( $out_of_stock_staus ));
wc_delete_product_transients( $product_id ); // Clear/refresh the variation cache
This is where it gets weird.
Updated sku
The data is showing correctly inside the product view in the admin panel. As a side note, this SKU can belong to a variation (we have tons of them) or it could be a simple product. In the end, they all seem to update ok. No errors are being generated that I can see.
I use a little PHP snippet in my functions.php that greys the out of stock items in the drop down. Here it is:
/* Grey out out of stock items in the product dropdown */
add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );
function grey_out_variations_when_out_of_stock( $grey_out, $variation ) {
if ( ! $variation->is_in_stock() )
return false;
return true;
}
So the issues are:
- The now out of stock item should not show as clickable in the dropdown, but it still is.
- The stock on the front end is not always saying zero, it lets you select one then says there is no stock, so the add to cart button is active and should not be. So the front end it not seeing the updates.
- The Woocommerce admin panel for products is not rolling up the out of stock to the parent, I have to do a quick edit and update for that to happen.
- Basically, the back end sees the changes, but the frontend is not really showing up correctly.
Any help that anyone can provide would be greatly appreciated!
Thank you
See Question&Answers more detail:
os