Random banner in Magento 1 using static blocks

The banners are an inevitable part of any E-Commerce store. They help to increase our sales by promoting new products, special offers & discounts etc.

Today I’m going to make a simple random banner in our Magento powered online store with static blocks and template files.

  • To add a random banner in Magento stores, first add few static blocks from administration panel (CMS->Static Blocks->Add new block).
  • When creating this static block, follow a common Identifier naming scheme for all these static block like

  • Normally we use images as banner & so insert our banner image on each static block.
  • Then wrap that image using anchor tag that target our specific page, product or category like

    <a href="http://mystore.com/my_new_product/"><img src="" alt="Some alt text"  /></a>
  • Now we just added an image link as our banner. But we have option to add text, buttons etc on that image with some CSS tricks & now that is purely off topic for me.
  • Then add a single line of code in our template file to echo a random static block.

    <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('BannerIdentifier_'.mt_rand(1, N))->toHtml() ?>

Here we use a PHP function, mt_rand() to achieve our goal. The mt_rand() return a random integer value between one and N because our parameters for mt_rand() function is one & N.

We use this returned integer value as a part of our static block identifier & echo that static block on that page.

To view our random banner, flesh the Magento cache and reload the store.

Recent Posts

  1. Replace string in multiple files - Command line
  2. Solve Grunt error - Port 35729 is already in use by another process
  3. Install WP-CLI
  4. Install LAMP - Apache2 , MariaDB, PHP 7 on Debian 8
  5. Enable / Disable Magento 2 module using command line

Questions / Comments

If you found this article interesting, found errors, or just want to discuss about them, please get in touch. Send an email to hello@sarathlal.com & I like your words.