3

in the front page, I have displayed multiple nodes (article) in the teaser view, each article has taxonomy.

I want to theme each node teaser according to the taxonomy it has, I think it can be done in the theme_preprocess_html(&$variables, $hook), for example

function theme_preprocess_html(&$variables, $hook) {
  if ($variables['is_front']) { 

    // something here, but I don't know what to do
  }
}

the first step is how to find all the nodes in the frontpage, the second is to get the taxonomy of each node, the third is to add the specific css class to each node according to the taxonomy of each node

Does any have suggestions?

1
  • Have you considered using drupal.org/project/views, it allows you to add a style to each row based on a property of a node.
    – Attiks
    May 23, 2012 at 18:13

2 Answers 2

2

Supposing that "field_tags" is the taxonomy field for which you want to use the taxonomy term values, you could use the following code.

function theme_preprocess_html(&$variables, $hook) {
  if ($variables['is_front']) {
    $terms = array();

    foreach ($variables['page']['content']['system_main']['nodes'] as $nid => $array) {
      $items = field_get_items('node', $array['#node'], 'field_tags');
      foreach ($items as $tid) {
        if (!isset($terms[$tid]) && ($term = taxonomy_term_load($tid))) {
          $terms[$tid] = drupal_html_class($term->name);
        }
      }
    }

    if (!empty($terms)) {
      foreach ($terms as $class_name) {
        $variables['classes_array'][] = $class_name;
      }
    }
  }
}
3
  • I am trying to understand what "my" taxonomy field is ("field_tags") in this context so I can change it, where can I see it? Or is there a way to avoid manually defining this in the code above? thanks Jan 15, 2015 at 12:10
  • 1
    It is shown in the page listing the fields used by a content type.
    – apaderno
    Jan 15, 2015 at 12:57
  • Thanks! When I add the code and change theme to mytheme as well as changing the taxonomy field it brakes the page and shows following error: Warning: Illegal offset type in isset or empty in MYTHEME_preprocess_html() (line 67 of ...\sites\all\themes\MYTHEME\template.php). which points to this line: if (!isset($terms[$tid]) && ($term = taxonomy_term_load($tid))) { do you have an idea why this error is shown? Jan 15, 2015 at 13:25
1

an easier way could be with views - you can create / enable a view that will replace the homepage. there you can add the taxo as a hidden field and use it in the class setting of the row

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.