Skip to content

Instantly share code, notes, and snippets.

@vensires
Created October 26, 2017 13:56
Show Gist options
  • Save vensires/a4b4db8df9666687d5b6f24555747736 to your computer and use it in GitHub Desktop.
Save vensires/a4b4db8df9666687d5b6f24555747736 to your computer and use it in GitHub Desktop.
Render a block in Drupal 7 anywhere in the page (eg. in a tpl.php file) with its title.
<?php
/**
* Render a block anywhere with its title.
*
* To render the block of the "ep_socialchannels" module with the
* "social_channels" delta, call this function, like this:
* @code
* THEME_render_block('ep_socialchannels', 'social_channels');
* @encode
*
* Take into account that this function hasn't been tested yet with blocks
* generated by the Views module! Also, since the code calls the function
* hook_block_list_alter() implementation of the block module, the block gets
* checked for page, user role, and user-specific visibility settings, resulting
* in removing the block if the visibility conditions are not met.
*
* @param string $module
* The machine name of the module which generates the block. Defaults to this
* module.
* @param string $delta
* The delta of the block. Defaults to this module's block.
*
* @return string
* The HTML of the rendered block.
*/
function ep_render_block($module, $delta) {
global $theme_key;
$query = db_select('block', 'b');
$result = $query
->fields('b')
->condition('b.theme', $theme_key)
->condition('b.module', $module)
->condition('b.delta', $delta)
->addTag('block_load')
->addTag('translatable')
->execute();
$block_info = $result->fetchAllAssoc('bid');
if (!$block_info) {
return '';
}
drupal_alter('block_list', $block_info);
$blocks = _block_render_blocks($block_info);
$build = _block_get_renderable_array($blocks);
return render($build);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment