I have below code in an script outside Magento to get products. It's working fine except it doens't return out of stock products.
How can I add out of stock products to the collection?
// Only gets in stock products
public function getProductsInStock() {
try {
$productCollection = $this->objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()
->addAttributeToSelect('sku')
->addAttributeToSelect('price')
->load();
} catch (\Exception $e) {
echo $e->getMessage();
}
return $collection;
}
EDIT: I just did some testing. It seems it has to do with following option in backend: Display Out of Stock Products
. When it is set to yes
the code returns all products instead of just the in stock
products.
Is it possible to ignore this setting in any way?
Best Answer
Option 1 You can use Magento\Catalog\Model\ResourceModel\Product\Collection according your needs. You can use can use it to get product data :
Option 2 : Also, You can try below code to get product collection, ( out side of magento ) though this is not best way
Update :