8

Is there a way to get disabled products programmatically in Magento 2 ?

2 Answers 2

6

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.

4

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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