Search code examples
drupaldrupal-7drupal-modulesdrupal-blocks

In Drupal 7, how do I get a list of all blocks being used on the page?


I'm building a module that manages ad units in the form of blocks that all need to be aware of each other and pass information around.

Thus I need to find a simple hook or other function to get a listing of every block that will be used on the page, so I can be sure to know the entire list of ad units on the page.

I've tried hook_block_list_alter() but this seems to return the ENTIRE list of blocks that exist in my Drupal install, with no designation of which blocks are actually going to be rendered or not on this page.

So, now what do I do?


Solution

  • I think it's got something to do with the order hook_block_list_alter() is called in but I'm not entirely sure. Either way the following code will get you a list of all blocks in the current page context. Be sure not to put this in a hook_block_list_alter() function or you'll get an exception caused by infinite nesting.

    global $theme;
    $all_regions = system_region_list($theme);
    $blocks = array();
    foreach (array_keys($all_regions) as $region) {
      $blocks += block_list($region);
    }
    

    If you only need the blocks in a particular region you can ditch most of the code above and just go with:

    $blocks = block_list('region_name');