Use WooCommerce function in other WordPress plugin

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/

2 Answers
2

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

Leave a Comment