How to Add block to cache in Magento 2

As we all know that are many cases in Magento 2 where product listing is too big that affects page load time. Now you can decrease the page load time by adding that specific block to the cache. Below are the different ways to achieve your goal:

Add a block to cache from layout xml:

Add below _construct() in your respected block file and specify cache_lifetime and a unique cache_tags cache identifier.

{{block name="explore-color-section" class="Companyname\Packagename\Block\Product\CustomProductCollection" product_id="51,52,53,54,55,56,57,58,59,60,40, 41, 42, 43, 44, 45, 46, 47, 70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90 ,91,92,93,94,95,96,97,98,99,100,101,102,103" cacheable="true" cache_lifetime="86400" template="Magento_Theme::html/explore_color_code.phtml"}}

Add a block to cache from block file:

Add the _construct () given below in your respected block file and specify cache_lifetime and a unique cache_tags cache identifier.

  /**
     * {@inheritdoc}
     */
    protected function _construct()
    {
        parent::_construct();
        $this->addData([
            'cache_lifetime' => 86400,
            'cache_tags' => ["explore_your_colors_ilnp"]]);
    }

Note: Here its _construct not __construct

Add a block having pagination to cache(Ex. Product listing with pagination):

Add the  _construct() given below in your respected block file and specify cache_lifetime and a unique cache_tags cache identifier.


 protected function _construct()
    {
        parent::_construct();
        $this->addData([
                'cache_lifetime' => 86400,
                'cache_tags' => [\Magento\Store\Model\Store::CACHE_TAG, \Magento\Cms\Model\Block::CACHE_TAG],
                'cache_key'  => "explore_your_colors_ilnp_".$this->request->getPost('page_number')
            ]
        );
    }

Lastly, run the command given below to make changes effective:

php bin/magento cache:clean
php bin/magento cache:flush
  • Share :