PHP / dynamic content in a static block – Magento

  • Facebook
  • Twitter
  • Delicious
  • Digg
  • StumbleUpon
  • Add to favorites
  • Email

What you may have noticed is that PHP code within static blocks are not supported in Magento, however there is a simple work around if you know how.

Create a static block by going to:

1
Admin -> CMS -> Static Blocks -> "Add New Block"

Fill in the standard information that is required, such a store views, title etc and make sure that the static block is set to enabled.

In the “content” section of the new static block add the following line:

1
{{block type="core/template" name="some_unique_name" template="myfolder/my_dynamic_php_content.phtml"}}

Note: template=”” is the location of your php file you wish to load inside your static block.

Save your new block.

Now that we have completed our static block, we need to make sure that our file (my_dynamic_php_content.phtml) exists in order for it to be loaded.

Open your FTP application and browse to:

1
app/design/frontend/YOUR_PACK/YOUR_THEME/template

Create your folder (if specified above)… in this case “myfolder” and upload your php file – i.e my_dynamic_php_content.phtml

Example:

1
2
3
4
5
<?php
    $i = 1;
    $i++;
    echo 'this is php content: ' . $i;
?>

And that’s is all there is too it. You should now see your php executed code within your static block.

Note: if you want to add a static block to a CMS page got to this article

4 thoughts on “PHP / dynamic content in a static block – Magento

  1. Hi Great post!

    There is also a post here:

    http://www.magentocommerce.com/boards/viewthread/422734/

    which refers to mutinyworks post here and another post :

    http://stackoverflow.com/questions/10288383/add-php-code-to-static-block

    I noticed the difference in your code
    `{{block type=”core/template”`
    vs
    `{{block type=”cms/block”`

    I followed your instructions and I was able to do simple php echo from my .phml file

    so I proved it worked – great!

    However as soon as I added a function like this
    `getAttributeText(‘Attribute Code’); ?>`
    OR
    `getData(‘Attribute Code’); ?>`
    it failed.

    I tested the code by adding the above php to my theme template view.phtml file

    getAttributeText returned value ‘Array’
    getData returned my ‘Product Features’ as bullet list – great!

    Can you explain why this php code does not work in the Static Block

    Magento ver. 1.7.0.2

  2. Sorry it does no look like the PHP code has come though on the post comment correctly – have emailed original text to contact us!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>