Tags

, ,

Sometimes it may happen that you need a different class for each content type nodes to write different CSS for them. And to achieve this most of the time we are overriding node.tpl file.

But there is a way to achieve the same and this is using Drupal preprocess function. function MY_THEME_preprocess_node(&$variables){}

Lets take an example: This example is for Drupal 7

Assume we have two content type #1: “Weekly Article” and #2: “Monthly Article”. Now we want add a class to first content type node “weekly-article” and to the second content type node “monthly-article” to achieve different fonts for these two type nodes. We will achieve this in a suitable manner. Let look at the below code:

function mytheme_preprocess_node(&$variables) {
  if ('weekly-article' == $variables['type']) {
    $variables['classes_array'][] = 'weekly-article';
  }
  elseif ('monthly-article' == $variables['type']) {
    $variables['classes_array'][] = 'monthly-article';
  }
  // Class for node type: "node-type-event" You can also just use the below commented code to do the same
  //$variables['classes_array'][] = 'node-'. $variables['type'];
}
Advertisements