You are here

function block_term_block_list_alter in Block Visibility by Term 7

Implements hook_block_list_alter().

Check the term specific visibilty settings. Remove the block if the visibility conditions are not met.

File

./block_term.module, line 107
Controls block visibility by term.

Code

function block_term_block_list_alter(&$blocks) {
  global $theme_key;

  // Build an array of terms for each block.
  $block_tids = array();
  $result = db_query('SELECT module, delta, tid FROM {block_term}');
  foreach ($result as $record) {
    $block_tids[$record->module][$record->delta][$record->tid] = TRUE;
  }
  $node = menu_get_object();
  if (!empty($node)) {
    $node_tids = array();

    // Get taxonomy_term_reference field names.
    $taxonomy_fields = db_query("SELECT field_name FROM {field_config} WHERE type = 'taxonomy_term_reference'");
    foreach ($taxonomy_fields as $field) {
      $terms = field_get_items('node', $node, $field->field_name);
      if (is_array($terms)) {
        foreach ($terms as $term) {
          $node_tids[$term['tid']] = TRUE;
        }
      }
    }
  }
  foreach ($blocks as $key => $block) {
    if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {

      // This block was added by a contrib module, leave it in the list.
      continue;
    }

    // If a block has no terms associated, it is displayed for every term.
    // For blocks with terms associated, if the term does not match
    // the settings from this block, remove it from the block list.
    if (isset($block_tids[$block->module][$block->delta])) {
      if (!empty($node)) {

        // This is a node or node edit page.
        if (!array_intersect_key($block_tids[$block->module][$block->delta], $node_tids)) {

          // This block should not be displayed for this term.
          unset($blocks[$key]);
          continue;
        }
      }
      else {

        // This is not a node page, remove the block.
        unset($blocks[$key]);
        continue;
      }
    }
  }
}