Programmatically: How to create a custom block in Magento
Step 1: Create a new PHP class
Create a new PHP file in the app/code/local/Mage/MyModule/Block directory (assuming your module name is MyModule). Name the file MyCustomBlock.php.
// app/code/local/Mage/MyModule/Block/MyCustomBlock.php
class Mage_MyModule_Block_MyCustomBlock extends Mage_Core_Block_Template
{
// Your block's code goes here
}
Step 2: Register the block in your module's config file
In your module's etc/config.xml file, add the following code:
<?xml version="1.0" encoding="UTF-8"?>
<blocks>
<mymodule>
<blocks>
<mycustomblock>
<class>Mage_MyModule_Block_MyCustomBlock</class>
</mycustomblock>
</blocks>
</mymodule>
</blocks>
Step 3: Use the block in your template
To use your custom block in a Magento template, you need to declare it in the layout file. For example, create a new file local.xml in your module's etc directory:
<!-- app/code/local/Mage/MyModule/etc/local.xml -->
<?xml version="1.0"?>
<layout>
<default>
<reference name="root">
<block type="mymodule/mycustomblock" name="mycustomblock" template="mymodule/mycustomblock.phtml"/>
</reference>
</default>
</layout>
Step 4: Create the template file
Create a new PHP file in the app/design/frontend/base/default/template/mymodule directory (or your theme's equivalent) named mycustomblock.phtml:
Welcome to my custom block!
This is my custom block.
That's it!
Now, when you navigate to your Magento store, you should see your custom block rendered at the top of the page.