5

I'm in the final stages of setting up my magento 2 store. In the backend I have a process using the API to keep stock information up to date. Sometimes the stock drops to 0 for every item in a category, making it empty. If you go to one of those categories you get:

We can't find products matching the selection. 

This makes sense, but I was wondering if there was a may to have magento hide the category altogether if the products in the category have no stock.

3 Answers 3

2

This extension hides the empty categories from navigation menu:

https://github.com/code-x/magento2-hide-empty-categories

2
  • 1
    Hey @mukesh, thanks for the response. I've downloaded and enabled the module, it seems to be working for the most part. There are still a couple of categories not being hidden but this is definitely a step in the right direction! Commented Jul 27, 2018 at 17:30
  • 1
    Link does not work anymore.
    – sv3n
    Commented Nov 5, 2022 at 18:45
0

From How to hide the categories which has no product from topmenu in Magento2

I already checked this but it hide the parent category as well even the child category have products

The mentioned extensions works only if empty parent categories are set to is_anchor.

Possible fix?

    /**
     * @inheritDoc
     */
    public function execute(Observer $observer)
    {
        $visibleCategories = [];

        /** @var Collection $categoryCollection */
        $categoryCollection = $observer->getDataByKey('category_collection');

        /** @var Category $category */
        foreach ($categoryCollection as $category) {
            if ($this->showCategory($category)) {
                $categoryId = $category->getId();
                $visibleCategories[$categoryId] = $categoryId;

                foreach ($category->getParentIds() as $parentId) {
                    $visibleCategories[$parentId] = $parentId;
                }
            }
        }

        foreach ($categoryCollection as $category) {
            if (!array_key_exists($category->getId(), $visibleCategories)) {
                $categoryCollection->removeItemByKey($category->getId());
            }
        }
    }

    /**
     * @param Category $category
     * @return bool
     */
    public function showCategory(Category $category): bool
    {
        return $category->getProductCollection()->count() > 0;
    }

Module

0

I tried this module, and it worked for me, for the most part. I believe this is the same GitHub repo as noted in the other answers to this question, I assume the author just changed the name, and that's why the other links don't work anymore.

Your Answer

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

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