2

I want to get disabled products for a category in product collection programatically in Magento 2.2.5. I am using following code:

 public function __construct(
    \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->categoryRepository = $categoryRepository;
    $this->productRepository = $productRepository;
}
public function deleteProductsByCategoryId($id)
{



    $category = $this->categoryRepository->get($id);
    $collection = $category->getProductCollection()->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
    foreach ($collection as $product) {
        // no disabled products are gotten
    }


}

But above code does not get disabled products.

1
  • Please check my answer. Sep 27 '18 at 16:40
0

Inject Magento\Catalog\Model\ResourceModel\Product\CollectionFactory in your construct and try to use this code :

protected $_productCollectionFactory;

public function __construct(
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Framework\View\Element\Template\Context $context
) {
    $this->_productCollectionFactory = $productCollectionFactory;
    parent::__construct($context);
}


public function getProductCollection($category_id_array)
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addCategoriesFilter(['in' => $category_id_array]);
    $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
    return $collection;
}

Remove var and generated folder and check it.

1
  • Hi @Rohan Hapani, I need to get all enabled and disabled products from a particular category. Is this any possible way? May 15 '20 at 12:04
-1

The following function is doing what you need:

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
    ) {
        $this->productCollection = $productCollectionFactory;
    }

public function deleteProductsByCategoryId($id)
        $productCollection = $this->productCollection->create();
        $productCollection->addAttributeToSelect('*');
        $productCollection->addCategoriesFilter(array('in' => array($id)));
        $productCollection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);

        foreach ($productCollection as $product) {
        }
    }

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.