I have created a custom block to display 10 random products on my homepage, and for load time etc, it is a bad idea to request random products from the database each load. Thus, have incorporated the default magento caching mechanism into my code to cache x versions of the block and rotate them for each user. But, I cannot get it to work correctly.

Currently, it loads random products A, B and C on first page load. Then loads new different random products ( products X, Y & Z) on the next page load. The page load after that loads the random products from the first load (A,B & C).

I cannot see where I have gone wrong thus was wondering if anyone could kindly help myself see my mistake.


    class Vish_RandomProduct_Block_Random extends Mage_Core_Block_Template{
            protected function _construct()
            'cache_lifetime' => 86400,
            'cache_tags'=> array(Mage_Core_Model_Store::CACHE_TAG, Mage_Cms_Model_Block::CACHE_TAG)
protected function _getRandomProductCollection()
    $numberOfItems = 12;

$productCollection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('name', array('nlike' => '%Adjustable Book Protection Jackets%'));
$candidateIds = $productCollection->getAllIds();
$numberOfProducts = count($candidateIds);
$chosenIds = [];
while ($numberOfItems) {
    $randomKey = mt_rand(0, $numberOfProducts - 1);
    if (!isset($chosenIds[$randomKey])) {
        $chosenIds[$randomKey] = $candidateIds[$randomKey];

    return $productCollection;
public function getCacheKeyInfo()
  $session = Mage::getSingleton('core/session');
  $counter = $session->getData('random_counter');
  $counter = ($counter + 1) % 10;
  $session->setData('random_counter', $counter);
  return array(


investigating further, via the placement of a mage::log, to see the count variable in the getCacheKeyInfo() function it reveals 3 entries each time I refresh. Little confused why this function is running this many times.

2017-11-21T20:11:45+00:00 DEBUG (7): 1 2017-11-21T20:11:45+00:00 DEBUG (7): 2 2017-11-21T20:11:45+00:00 DEBUG (7): 3

Rest of the block code:


$collection = $this->_getRandomProductCollection(); 
//  Mage::log("template for random called", null, 'randomprodcachelog.log');
<?php if ($collection->getSize() > 0): ?>
     <div class="jcarousel-wrapper">
                <div class="jcarousel">
                           <?php foreach ($collection as $_product) {  ?>

                        <li><a href="<?php echo $_product->getProductUrl() ?>">
                        <img src='media/wysiwyg/805.svg' data-src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(200); ?>" alt="" /></a> 

                        <div class="productName">

                        <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $_product->getName(); ?></a><br/>
                        <?php if($this->htmlEscape($_product->getExtraInfo() !="")):?>
                            <span class="icon icon-info-circle tooltip" title="<?php echo $this->htmlEscape($_product->getExtraInfo())?>" ></span>
                            <?php endif;?>

                        <div class="productCode">
                    <?php echo $this->__('Product Code: ') . $this->htmlEscape($_product->getData('sku'));?>
                         <?php if($_product->isSaleable()): ?>
                        <p><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Basket') ?></span></span></button></p>
                    <?php else: ?>
                        <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                    <?php endif; ?>

                    <ul class="add-to-links">
                        <?php if ($this->helper('wishlist')->isAllow()) : ?>
                            <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                        <?php endif; ?>


                         <?php }?>

                <a href="#" class="jcarousel-control-prev">&lsaquo;</a>
                <a href="#" class="jcarousel-control-next">&rsaquo;</a>


<?php endif;?>


<?xml version="1.0"?>

1 Answer 1


Solution 1:

protected function _construct()
    'cache_lifetime' => 3600,
    'cache_tags'     => array(Mage_Catalog_Model_Product::CACHE_TAG),
    'cache_key'      => $this->getProduct()->getId(),

Solution 2:

    <reference name="root">
        <block type="type/block" name="my.block" template="path/to/bock.phtml">
           <action method="setCacheLifetime"><lifetime>3600</lifetime></action>
  • Prince why the '$this->getProduct()->getId()'? the custom block is added into my home cms page Nov 21, 2017 at 14:57
  • It is a cache identyfier
    – PЯINCƎ
    Nov 21, 2017 at 15:05
  • Prince please see updated question Nov 21, 2017 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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