Magento 2.1.1.
I have added custom sorting of products in catalog pages, by random order and I want my block to be dynamicall, so with every change of sorting for random the collection should be shuffled.
I would like to set cache lifetime for block in layout xml if possible. I can exclude it completly from caching using `cacheable="false", but that's not exactly I need. I have noticed something like this:
<block class="Magento\Theme\Block\Html\Topmenu" name="catalog.topnav" template="html/topmenu.phtml" ttl="3600" before="-"/>
I am not sure how to test if it working - I set 15 seconds for my block, but actually order of product never changed.
If I find out how to set TTL for block, a nice improvement would be one from here: https://www.schmengler-se.de/en/2015/09/show-random-products-in-magento-you-are-doing-it-wrong/
First, make sure that you don’t load random products on every request. Use the cache. Even with a cache lifetime of just a few minutes, this will reduce the load on a frequently visited page significantly. If you want to avoid showing the same products to the same user on a page refresh, you can cache multiple versions of the block using different cache keys and select one of the tags based on time, a counter in the session, or randomly.
The following method in a block caches 10 versions of the block and rotates them for each user. With a low cache lifetime most users will not see the same version twice:
In a similar situation, I can add my block in a few versions to cache (preventing the same user watching the same order of products), but I don't know how to achieve that.
2 Answers 2
Try This
app/code/VendoreName/ModuleName/etc
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Theme\Block\Html\Topmenu" type="VendoreName\ModuleName\Block\Html\Topmenu" />
</config>
app/code/VendoreName/ModuleName/Block/Html
Topmenu.php
<?php
namespace VendoreName\ModuleName\Block\Html;
class Topmenu extends \Magento\Theme\Block\Html\Topmenu
{
protected function getCacheLifetime()
{
return null;
}
}
now run php bin/magento cache:clean command and check.
For Topmenu you should override \Magento\Theme\Block\Html\Topmenu:
protected function getCacheLifetime(){
return null;
}
-
1Beware of performance problemsAlex– Alex2018年11月02日 16:09:48 +00:00Commented Nov 2, 2018 at 16:09
ttlattribute. Please post your answer.