8

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

Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352
Gael COAT
  • 387
  • 4
  • 14

2 Answers2

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.

Khoa TruongDinh
  • 32,054
  • 11
  • 88
  • 155
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();
Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352