Skip to content

Get current category on category page & performance – Magento 2.4

Currently we created a custom module, to get the current_category using code below on the category page.

Then we created multiple widgets in the backend, that implement a block to load on specific category pages.
These blocks load custom phtml files, where we load the getCurrentCategory() value.

But because we use multiple custom phtml files, that all load the getCurrentCategory() value, we think this can be improved for performance.

But what is the best way to achieve this? Because we load it by a widget. For example using getViewModel?

Code:

namespace ModuleCategoryInfoBlock;
use MagentoFrameworkRegistry;

class Category extends MagentoFrameworkViewElementTemplate
{
    private $registry;
    
    public function __construct(Registry $registry) 
    {
        $this->registry = $registry;
    }

    public function getCurrentCategory()
    {        
        return $this->registry->registry('current_category');
    } 

}

phtml:

<?php
$categoryhelper = $block->getLayout()->createBlock('ModuleCategoryInfoBlockCategory');
$category = $categoryhelper->getCurrentCategory();
?>