Magento random block generator / block randomiser

This could be pretty useful if you want to combine XML block control with a random content display (eg. banner ads). Very easily achieved, simply create 1 file in ./base/default/template/page/html/random_block.phtml
  if(is_array($children)) {
    echo $this->getChildHtml($children[0]); 
Then in your relevant XML file - control the output by using:

    some alt text
    link url
    some alt text
    link url

You can add any type of block you want and it will just grab one at random. [syntaxhighlighter]
  • Thank you for this posting. Please forgive my ignorance - I created the random.phtml.

    I want to now place the code in the "relevant xml" file. How do I know what the relevant file is? Would it be catalog.xml ? Can I put this code in a cms block?

    What I would really like to do - is have a folder ie - banners - and have it randomly pick a banner from the folder everytime the page is refreshed...Will this do that? I will have up to 25 different banners.
    I am a graphics designer turned into a magento admin LOL. I have figured out many things - but until I can afford the Zend class to learn php - the manipulation of the code is slightly out of my comfort zone.

    Any help is appreciated!

    Traci Kaspar
    Creative Designer

    • Hi Traci,

      The relevant file would be the file for the module where you want the content to appear.

      cms.xml - for cms pages
      catalog.xml - for catalogue pages
      catalogsearch.xml - for search result pages

      If you want it on all pages, then pop it in the tag at the top of any .xml file.

  • Robert


    Very nice piece of code!

    Only one question, how can i use this when i want to show for example 5 images?

    i have 1 folder full of images and want to show 5 at the SAME time but rondom from the whole folder.

    Hope you can help me.

    Thanks in advance!

    Greets, Robert

    • Hi Robert,

      You would be better off just using a standard core/template call to a custom template with scan_dir and reduce the array to 5 items, then output with implode() or foreach

  • ilnar

    You're shuffling whole array just to select one random element. Very nice approach..

    • True, you could just use array_rand - but the original purpose for this code required a number of elements to be displayed (we're just posting a code snippet here).