• Resolved Ruben

    (@rbnmo)


    Hello,

    I’m trying to update variable product stocks through php with this function:
    wc_update_product_stock($post_id, $qty, ‘set’, false);
    But I sometimes end up with the stock status showing “Out of stock (3)” – so it has stock but it shows the wrong status.

    I believe it doesn’t updated the stock status when it goes back in stock from 0.

    I also tried:
    wc_update_product_stock($post_id, $qty, ‘set’, true);
    but it still didn’t work.

    How can I tell it to update the stock status? Is there a better way to quickly update stocks programmatically on multiple products through a cron job?

    Thank you!

    WooCommerce Version 4.0.1

Viewing 7 replies - 1 through 7 (of 7 total)
  • After changing product data programatically, ensure you have deleted the relevant transient:
    wc_delete_product_transients( $post_id );
    This will force the data to be re-evaluated the next time the product is queried.

    Thread Starter Ruben

    (@rbnmo)

    Thank you very much, lorro!
    I will try that and get back to you if it doesn’t work.

    Plugin Support Tseten a11n

    (@tibetanitech)

    We haven’t heard back from you in a while, so I’m going to mark this as resolved – if you have any further questions, you can start a new thread.

    Thread Starter Ruben

    (@rbnmo)

    Tried it and it still doesn’t work:

    $new_stock = wc_update_product_stock($post_id, $qty, 'set', false);
    wc_delete_product_transients($post_id);

    I see this:
    Out of stock (8)
    Out of stock (3)
    etc..

    Thread Starter Ruben

    (@rbnmo)

    I found out the issue. It was because the product is a variable product but has no variations.

    Hello,

    I have the same issue. On Simple products my code works but on Variations the _stock_status is not updated.
    For example, if the stock quantity of a Variation is 30 and I change it to 0 with my code, the _stock_status remain “instock” instead of “outofstock”.

    My code is:

    $product = wc_get_product( $variant_post_id );  
    wc_update_product_stock( $product,  $qty_new , 'set' );
    wc_delete_product_transients( $variant_post_id );

    Thanks!

    WooCommerce version 4.5.2

    Also see this nice CRUD example here: https://stackoverflow.com/a/51940564/696680

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Update stock programmatically’ is closed to new replies.