Magento Tutorials Accessing Static Blocks In Magento

« Back to Magento Tutorials

Sometimes a client asks to be able to manage certain areas of their Magento ecommerce website that would usually require access to template files. While this is okay, most clients consider HTML a foreign language and would probably do more harm than good. To remedy this, a lot of developers would consider creating a custom module. While this isn't bad, sometimes it can require too much work if the client only wants to change one line of text! A much easier and quicker solution is to use a static block. Static Blocks can be included into your design in three main ways:

  • Inside a template file using PHP
  • Inside a content field of a CMS Page in the Magento admin
  • Inside the Layout Update XML field of a CMS page in the Magento admin

Accessing a Magento Static Block From a PHP Template File

To access the block's content from a .phtml template file, use the following code.

	// Retrieve the layout object
	$layout = Mage::getSingleton('core/layout');
	// Generate a CMS block object
	$block = $layout->createBlock('cms/block');
	// Set the block ID of the static block
	// Write the static block content to screen
	echo $block->toHtml();

Copy the above code into a Magento template file and change your 'block-id-in-magento' to the static block you want to include. Depending on which template you add this to, you may need to refresh the Block HTML Cache option in the Magento Admin.

Accessing a Magento Static Block From A CMS Page

If you have created a CMS page in the Magento administration, sometimes you may want to add a static block inside of it. To accomplish this, you could either add a line of code into the content field or add it to the custom layout xml field.

Add a Static Block to the CMS Page Content Field

 * {\{block type="cms/block" block_id="block-id-in-magento"}}

Adding a Static Block to the CMS Page Layout Update XML FIeld

<reference name="content">
  <block type="cms/block" name="">
    <action method="setBlockId"><block_id>block-id-in-magento</block_id></action>

Magento Static Blocks: Conclusion

This tutorial is short but hopefully illustrates the many ways of accessing static blocks programmatically. Each method has it's advantages and disadvantages so consider which one is best for the functionality you are trying to achieve.

Post your comment

FishPig Ltd