Is there a way to get disabled products programmatically in Magento 2 ?
2 Answers
You can try with:
/** @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $_productCollectionFactory **/
$this->_productCollectionFactory->create()
->addAttributeToSelect('*')
->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
Need to inject \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $_productCollectionFactory
in your constructor.
It's best practice to use the Service Contracts Layer (see here: Magento 2: what are the benefits of using service contracts?)
protected $_productRepository;
protected $_searchCriteriaBuilder;
public function __construct(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->_productRepository = $productRepository;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder;
}
Then in your code you can do:
$searchCriteria = $this->_searchCriteriaBuilder->addFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED, 'eq')->create();
$searchResults = $this->_productRepository->getList($searchCriteria);
$disabledProducts = $searchResults->getItems();