1

I have a lot of products on my webshop, and so many of them are inactive, but will come back later.

I wonder if it's possible to show only numbers of active products besides each category? maybe a custom module is needed for this? If so, what do I need to do?

enter image description here

It's OK to still show all products inclusive the inactive ones on the right side after clicking on the categories. It's only the overview on the left site I need to change.

2

You need to override Catalog Block File : vendor/magento/module-catalog/Block/Adminhtml/Category/Tree.php

Add

protected $_productCollectionFactory;

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

Replace

public function buildNodeName($node)
{
    $result = $this->escapeHtml($node->getName());
    if ($this->_withProductCount) {
        $result .= ' (' . $node->getProductCount() . ')';
    }
    return $result;
}

With

public function buildNodeName($node)
{
    $result = $this->escapeHtml($node->getName());
    if ($this->_withProductCount) {
        $result .= ' (' . $this->getEnabledProducts($node->getId()) . ')';
    }
    return $result;
}

Add New Function

public function getEnabledProducts($id)
{
    $category = $this->_categoryFactory->create()->load($id);
    $collection = $this->_productCollectionFactory->create();
    $collection->addCategoryFilter($category);
    $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
    return $collection->count();
}

Now you are get only enabled products count.

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.