0
votes

I have a php cron job that is updating product information from a 3rd party vendor. These changes can be price, sale price, stock, etc.

I have everything running except when I go to put a product on sale via the following code:

 update_post_meta( $product_id, '_sale_price', $sale_price );
 update_post_meta( $product_id, '_price', $sale_price );

the product is updated correctly and shows the sale price in the product on the website and the product admin. When I go to use one of the shortcodes for woocommerce to display products on sale it does NOT pull back what was updated via the above code, ONLY if it was done through the admin panel.

[products limit="24" columns="4" on_sale="true" ]

So my code is not doing something woocommerce does, but I have no idea what it is I am missing. My only fix so far I have found is to remove the sale price in the admin panel->save and then add it back->and save again. Since there are 18,000+ variations on 3,000+ products this is not something that can be done by hand.

As an aside: I had this problem with WP all import too when we imported vis csv file feeds.

Any ideas or thoughts would be helpful.

Thanks!

1
Woocommerce caches the product data for performance, so directly updating the meta will not update the cache. Use of the CRUD methods in LoicTheAztec's answer will.Peter HvD
@PeterHvD Unfortunately CRUD is not working inside my CRON job. Woocommerce throws an error.Dave

1 Answers

4
votes

The best way should be to use CRUD methods introduced with Woocommerce 3… But as it is in a cron job, I am not sure that it will work. Anyway try the following:

// Get an instance of the WC_Product object
$product = new WC_Product( $product_id );

// Set product prices
$product->set_sale_price( $sale_price );
$product->set_price( $price );

// Save data and update caches
$product->save();

Now depending on the product type, you might be need to call the product object instance differently…