As we all know there are many cases in Magento 2 development where the product listing is too big which 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
Related resources:
Post a Comment
Got a question? Have a feedback? Please feel free to leave your ideas, opinions, and questions in the comments section of our post! ❤️