Task

On a recent project a client asked for the following: when visiting a taxonomy term, if that term has children, to display a new block displaying the children terms. The block would also need to have the parent term as the title.

Step 1: Function

Inside your template.php file add the following:

<?php
function themename_child_terms($vid = 1) {
  if(
arg(0) == 'taxonomy' && arg(1) == 'term') {   
   
$children = taxonomy_get_children(arg(2), $vid);
      if(!
$children) {
       
$custom_parent = taxonomy_get_parents(arg(2));
         
$parent_tree = array();
          foreach (
$custom_parent as $custom_child => $key) {
           
$parent_tree = taxonomy_get_tree($vid, $key->tid);
          }
         
$children = $parent_tree;
      }
  
   
$output = '<ul>';
    foreach (
$children as $term) {
     
$output .= '<li>';
     
$output .= l($term->name, 'taxonomy/term/' . $term->tid);
     
$output .= '</li>';
    }
   
$output .= '</ul>';
   
    return
$output;
  }
}
?>

Step 2: New Block

Create a new block and add the following to the block body. (Be sure to select the input as PHP):

<?php // $vid is the vocabulary id.
   
print themename_child_terms($vid = 1);
?>

Step 3: Alter Block Title

Create a block-block-blockid.tpl.php file inside the default theme directory. Put the following inside the new file:

<div id="block-<?php print $block->module .'-'. $block->delta; ?>" class="block block-<?php print $block->module ?>">
<?php // let's get the parent term title for the child term we are visiting
       
$parent_title = array_reverse(taxonomy_get_parents_all(arg(2)));
        if(
$parent_title) {
           
$block->subject = $parent_title{0}->name;
        }
   
?>

<?php if ($block->subject): ?><h2><?php print $block->subject ?></h2><?php endif;?>
<div class="content">
<?php print $block->content; ?>
</div>
</div>

Tip

The function could be added to the block body (block edit form) instead of the theme's template.php file. Calling the function inside the template.php file will create an extra step of security, preventing the admin/client from breaking the block (accidentally altering/removing the function) when editing.

Name
E-mail (Kept Private)
CAPTCHA
Are you human?
Image CAPTCHA