The following setup script will create a static block programatically. There are a few reasons why it’s a good idea to create static blocks this way.
- You don’t have to manually add the static blocks to all of your environments i.e. local, staging, production
- Any developer that pulls your code is working with the same dataset without having to retrieve a database dump
- You wont get errors if you are trying to retrieve a static block that doesn’t exist.
- The data is version controlled
- On a multi-store site may have to create a static block for each store-view which is tedious
For example, I commonly have to add a static block for links in the footer so that the client can update them at will.
The below script loops through each of your stores and creates a static block for each. Uncomment the line $stores = array(0); in order to create a single static block used for all store views.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php /** * This should be placed in the data/ directory for example * data/[module]_setup/data-upgrade-1.0.4-1.0.5.php */ $content = ' <div class="row"> <div class="columns small-12 medium-4"> <h3>Block 1</h3> </div> <div class="columns small-12 medium-4"> <h3>Block 2</h3> </div> <div class="columns small-12 medium-4"> <h3>Block 3</h3> </div> </div> '; //if you want one block for each store view, get the store collection $stores = Mage::getModel('core/store')->getCollection()->addFieldToFilter('store_id', array('gt'=>0))->getAllIds(); //if you want one general block for all the store views, uncomment the line below //$stores = array(0); foreach ($stores as $store){ $block = Mage::getModel('cms/block'); $block->setTitle('Your title'); $block->setIdentifier('your_identified'); $block->setStores(array($store)); $block->setIsActive(1); $block->setContent($content); $block->save(); } |
Magento Create Static Block With Setup Script