2

I am currently trying to make a plugin which updates the stock count of my WooCommerce products. So I wanted to access the wc_update_product_stock function, but an error got returned instead.

Code in plugin php file:

wc_update_product_stock($id,$stock);

error in log:

Fatal error: Call to undefined function wc_update_product_stock()

I read somewhere, that a normal call of all WC functions should be possible, if the WooCommerce Plugin is activated.

Update:

I tried your code inside a function as Scriptonomy suggested

    function updateWCProduct($product)
    {         
        $wcproduct = new WC_Product($product->get_id());
        var_dump($wcproduct);
        $wcproduct->set_stock($product->get_stock(),'set');
        $wcproduct->set_price($product->get_price());
    }

but I get a empty product object back

object(WC_Product)#9573 (5) { ["id"]=> int(9834) ["post"]=>
NULL ["product_type"]=> NULL ["shipping_class":protected]=>
string(0) "" ["shipping_class_id":protected]=> int(0) }

Update: To get the product by sku use the code here: https://www.skyverge.com/blog/find-product-sku-woocommerce/

1

If you've already invoked the product, e.g. with

$product = new WC_Product($id);

then you can update the stock level with

$product->set_stock($stock);

For more information check the documentation:

https://docs.woothemes.com/wc-apidocs/class-WC_Product.html#_set_stock

  • This answer doesn't work for me. I have the product (I'm logging it out and I can see all its attributes), $stock is a valid integer, and I get no errors in the log when I do $product->set_stock($stock); but the change is just not written to the DB. What could be going wrong? – pjv Nov 20 '15 at 20:11
  • Arggghh. Never mind the comment above. I was trying to set_stock() on a product that did not have managing_stock set to yes. Toggled that and now this works perfectly. – pjv Nov 20 '15 at 20:46
  • set_stock works for me but set_price doesn't, not sure whats wrong. – Nimbuz Oct 31 '16 at 5:28
2

The Woocommerce plugin must be loaded and initiated before you can call any functions of the sort.

Hook onto the woocommerce_init action and execute your code there.

add_action( 'woocommerce_init'

  • Valid point from your side! – Josef Rosel Nov 10 '15 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.