2

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, nice improvment 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 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 similiar 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.

  • Did you find an answer here? – Stevie G May 18 '17 at 20:34
  • Actually I have done it in a little different way, not using ttl of block cache. – Bartosz Kubicki May 19 '17 at 6:51
  • So you removed the ttl attribute. Please post your answer. – Stevie G May 19 '17 at 9:11
  • actually I don't have answer for this question only I figured out way to implement random sorting which works with cache. – Bartosz Kubicki May 19 '17 at 10:21
1

For Topmenu you should override \Magento\Theme\Block\Html\Topmenu:

protected function getCacheLifetime(){
    return null;
}
  • 1
    Beware of performance problems – Alex Nov 2 '18 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.