Advertising sustains the DA. Ads are hidden for members. Join today

Tag-sensitive beans

Last updated on
8 December 2018

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

If you want blocks to be shown only on pages with specific tags, this is an example implementation.

This will insert beans with the tag-field enabled into a page with similar tags.
It is assumed that both bean type and node type has field_tags.

The bean type is called tag_sensitive_block, and the code simply calls for all beans of this type and collects those that share a tag with the current node. Then it inserts $max_beans beans into the first and second sidebar, switching between them after each insert.


/**
 * Implements hook_page_build().
 */

 function my_module_page_build(&$page) {
  
  if ($node = menu_get_object()) {
   
   //get taxonomy terms for current node
   $tids = array();
   
   $field = $node->field_tags;
   
   if (isset($field['und'])) {
    
    $node_terms = $field['und']; //und is undefined language, replace as necessary
    
    foreach ($node_terms as $node_term) {
     $tids[] = $node_term['tid'];
    }
    
    //get list of relevant tag-sensitive blocks
    $query = new EntityFieldQuery();
    
    //get beans with tids that match node tids
    $result = $query
     ->entityCondition('entity_type', 'bean')
     ->entityCondition('bundle', 'tag_sensitive_block')
     ->fieldCondition('field_tags', 'tid', $tids)
     ->execute();
    
    //get bean ids
    if (isset($result['bean'])) {
     
     $bids = array_keys($result['bean']);
     
     //populate left and right sidebar with beans
     $left_sidebar = true; //alternate between first and second sidebar
     $max_beans = 6; //maximum 3 beans in first sidebar, 3 beans in second sidebar
     $bean_counter = 0;
     
     foreach($bids as $bid) {
      
      //stop at max beans
      if ($bean_counter > $max_beans) {
       break;
      }
      
      //load bean
      $bean_array = entity_load('bean', array($bid));
      $bean = $bean_array[$bid];
      $bean_delta = 'delta';
      $delta = $bean->$bean_delta;
      
      //determine placement
      if ($left_sidebar) {
       
       $page['sidebar_first'][$delta]['content']['#markup'] = drupal_render(bean_view($bean));
       $left_sidebar = false;
       
      } else {
       
       $page['sidebar_second'][$delta]['content']['#markup'] = drupal_render(bean_view($bean));
       $left_sidebar = true;
       
      }
      
      $bean_counter += 1;
     }
    }
   }
  }
 }

Help improve this page

Page status: No known problems

You can: