I need to be able to programmatically update product stock in my Cron job. I have an array that contains both the SKU of the product needing updating and the Stock value of that product. How can I select a product by SKU and then update the stock?


I'm not sure about your data array which contains the SKU product and Stock value. So, I will use simple data.

We can update product stock via API:



        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        //Our sample values
        $sku = '100098';
        $stockValue = 5;

        $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
        $stockRegistry = $objectManager->create('Magento\CatalogInventory\Api\StockRegistryInterface');

        //Load product by SKU
        $product = $productRepository->get($sku);
        //Need to load stock item
        $stockItem = $stockRegistry->getStockItem($product->getId());
        $stockItem->setData('qty',$stockValue); //set updated quantity


        $stockRegistry->updateStockItemBySku($sku, $stockItem);

You can quick test our code lines by using playground:

How can I bootstrap Magento 2 in a test.php script?


  • This looks like it would work, however I keep getting the "Class 'Magento\Framework\App\ObjectManager' not found" message.
    – opqr549
    Aug 1 '16 at 15:18
  • I have just update my code. Aug 1 '16 at 15:40
  • $objectManager=\Magento\Framework\App\ObjectManager::getInstance(); This is the line that is throwing the error.
    – opqr549
    Aug 1 '16 at 15:51
  • Tried to clear Magento Cache? How you test my code? Aug 2 '16 at 12:49
  • I am running the code in my cron job script located in Custom/Module/Cron/Script.php. Something tells me I am missing some sort of dependency injection or something like that. I have tried clearing the cache. Thank you for your help!
    – opqr549
    Aug 2 '16 at 19:16

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.