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();
      break;
  }

  return $block;
}

function _YOUR_MODULE_BLOCK_ABC_CONTENT() {
  $output = t('Hello world');
  return $output;
}

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

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..

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?

admin's picture

Hey Travis,

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

(There is no closing

markup)

Aaqib's picture

Hi,

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 ?

Thanks

Add new comment