[Drupal] How to create a custom block programatically in Drupal 6

| | 2 min read

There is no Drupal website with out a block. As a Drupal developer there are certain cases we need to create custom blocks programatically. While working in a project I faced an issue with a custom Drupal block creation in Drupal 6 version. I think some of you also faced the same situation,Custom block creation in Drupal 6 is not a big issue. I think the below code will help to handle the situation.


       /**
	* Implementation of hook_block()
	*/
	function mymodule_block($op='list', $delta=0, $edit=array()) {
	  // Declare the list of blocks to create
          if ($op == 'list') {
	    $blocks = array();
	    $blocks['custom_block1'] = array(
	      'info' => t('Mymodule block1 infromation.'),
	    );
	    $blocks['custom_block2'] = array(
	      'info' => t('Mymodule block2 infromation.'),
	    );
	    $blocks['custom_block3'] = array(
	      'info' => t('Mymodule block2 infromation.'),
	    );
	    return $blocks;
	  }
	  // in this case assign the content for the listed block
	  elseif ($op == 'view') {
	    switch ($delta) {
	      case 'custom_block1':
	      // assign the value for the custom blocak one.
	      $block = array(
	        'subject' => t('Title for  custom block1'),
	        'content' => "content of custom_block_one" ,
	      );
	      break;
	      case 'custom_block2':
	      // assign the value for the custom blocak two.
	      $block = array(
	        'subject' => t('Title for custom block2'),
	        'content' => "content of custom_block_two" ,
	      );
	      break;
	      case 'custom_block3':
	      // assign the value for the custom blocak two.
	     $block = array(
	       'subject' => t('Title for custom block3'),
	       'content' => "content of custom_block_three" ,
	     );
	     break;
	  }
	  // Values of the blocks are passed using the variable $block
	  return $block;
	  }
	}

The above code will create the blocks and We can choose sidebar first or second or as main contents depends upon your requirement.

Clear the theme registry to get the result properly.