Create a Custom Block Programmatically

Public

Generate a custom block with a simple function wrapper around block_add_block_form_submit();

</> CopyGet raw version
php
  1. <?php
  2.  
  3. function create_block($attributes=array()) {
  4.  
  5. // Defaults
  6. $defaults = array(
  7. 'title' => 'Title',
  8. 'desc' => 'Generated Block',
  9. 'body' => 'body',
  10. 'format' => 'filtered_html',
  11. 'visibility' => 0,
  12. 'pages' => '', // path
  13. 'custom' => 0,
  14. 'module' => 'block',
  15. 'roles' => array(),
  16. 'regions' => array(),
  17. );
  18.  
  19. // Attributes
  20. $attr = array(
  21. 'title' => (isset($attributes['title']))?$attributes['title']:$defaults['title'],
  22. 'desc' => (isset($attributes['desc']))?$attributes['desc']:$defaults['desc'],
  23. 'body' => (isset($attributes['body']))?$attributes['body']:$defaults['body'],
  24. 'format' => (isset($attributes['format']))?$attributes['format']:$defaults['format'],
  25. 'visibility' => (isset($attributes['visibility']))?$attributes['visibility']:$defaults['visibility'],
  26. 'pages' => (isset($attributes['pages']))?$attributes['pages']:$defaults['pages'],
  27. 'custom' => (isset($attributes['custom']))?$attributes['custom']:$defaults['custom'],
  28. 'module' => (isset($attributes['module']))?$attributes['module']:$defaults['module'],
  29. 'roles' => (isset($attributes['roles']))?$attributes['roles']:$defaults['roles'],
  30. 'regions' => (isset($attributes['regions']))?$attributes['regions']:$defaults['regions'],
  31. );
  32.  
  33. // load the function
  34. module_load_include('inc', "block", "block.admin");
  35.  
  36. // make believe variable
  37. $form_state = array();
  38.  
  39. // Fill variable
  40. $form_state['values']['title'] = $attr['title'];
  41. $form_state['values']['info'] = $attr['desc'];
  42. $form_state['values']['body']['value'] = $attr['body'];
  43. $form_state['values']['body']['format'] = $attr['format'];
  44. $form_state['values']['visibility'] = $attr['visibility'];
  45. $form_state['values']['pages'] = $attr['pages'];
  46. $form_state['values']['custom'] = $attr['custom'];
  47. $form_state['values']['roles'] = $attr['roles'];
  48. $form_state['values']['module'] = $attr['module'];
  49. $form_state['values']['regions'] = $attr['regions'];
  50.  
  51. // Create block
  52. block_add_block_form_submit(array(), $form_state);
  53. }
  54.  
  55. // Example Usage:
  56.  
  57. create_block(array(
  58. 'title' => 'Hello World',
  59. 'desc' => 'Hello World - Generated Block',
  60. 'body' => 'Hello World - Body',
  61. ));