/** * Add list of associated identities to the top menu block for caching purposes. * * @param \Magento\Theme\Block\Html\Topmenu $subject * @return void */ public function beforeGetIdentities(\Magento\Theme\Block\Html\Topmenu $subject) { $subject->addIdentity(Category::CACHE_TAG); $rootId = $this->storeManager->getStore()->getRootCategoryId(); $storeId = $this->storeManager->getStore()->getId(); /** @var \Magento\Catalog\Model\ResourceModel\Category\Collection $collection */ $collection = $this->getCategoryTree($storeId, $rootId); $mapping = [$rootId => $subject->getMenu()]; // use nodes stack to avoid recursion foreach ($collection as $category) { if (!isset($mapping[$category->getParentId()])) { continue; } $subject->addIdentity(Category::CACHE_TAG . '_' . $category->getId()); } }