Create your own custom Drupal block programmatically

Super duper simple example on how to programmatically create your own custom Drupal blocks and display any content.

Code snippet below needs to be in a custom module.

* Implements hook_block_info().
function YOUR_MODULE_block_info() {
  $blocks = array();

  $blocks['YOUR_BLOCK_ABC'] = array(
    'info' => t('YOUR BLOCK NAME'),

  return $blocks;

* Implements hook_block_view().
function YOUR_MODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'YOUR_BLOCK_ABC':
      $block['subject'] = '';
      $block['content'] = _YOUR_MODULE_BLOCK_ABC_CONTENT();

  return $block;

  $output = t('Hello world');
  return $output;

13 comments for 'Create your own custom Drupal block programmatically'

Karl's picture

Thanks for this.

senorincognito's picture

For some reason I had real trouble doing this. The example block didn't work for some reason, while this worked like a charm. Thank you for that.

admin's picture

I honestly don't know if its possible to directly use #attached into the hook_block_view.

But what you can do, if your block content is coming from another callback like Form API, attach it there instead.

Or simply, drupal_add_css().

ARUN's picture

I have tried this code in my drupal 6 website. But it is not woking. I have implemented this code in my custom module and clear the cache. But still the block name is not showing in admin/build/block page. Please help me.

admin's picture

Dear Arun,

Sorry but the code snippet is for Drupal 7 only as tagged in the post..

James's picture

How do I go about programmatically deleting the blocks I create?

admin's picture

When you uninstall or remove this hook_block_info(), it will not appear in your Block list anymore.

Travis Johnston's picture

I was able to create a custom Facebook module using your code, thanks! But when I want to test my block, but placing it inside of a region, it loads at the top of the page outside of the theme with no block wrappers or anything. All tags are closed accordingly.

Do I need to also add a block.tpl file to the module?

Travis Johnston's picture

Looks like it has to do with HTML inside of the contents function. Maybe I need to load a block template here and place my html/php mix for facebook onto that page.

admin's picture

Hey Travis,

I have a feeling your HTML content inside of your block wasn't really closed properly.

(There is no closing


Aaqib's picture


I've tired the coded, worked great. I need to add a text editor, so i can add php code and select php code as text format. Is it possible in custom block ?