Give your Nodes some Class

In this short tutorial I'm going to show you how to set a unique class on your nodes based on taxonomy terms, which is something I've been asked about more than once or twice.

First thing you need is a template.php file and inside that declare a preprocess function. We're going to use this function to build an array of class names and then print them in node.tpl.php. With me? Ok.

Since taxonomy terms can contain spaces and punctuation they don't make particularly good class names so we'll need to clean them up before printing them in the node template. We'll use this nifty little function to do just that, and call this function to do its cleaning when we need it, so for now place this in your template.php file and forget about it.

 * Clean a string of unwanted characters.
 * @param $string
 *   The string
 * @return
 *   The converted string
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9-]+/', '-', $string));
  if (!
ctype_lower($string{0})) {
$string = 'id'. $string;

Next we need to create the preprocess function in template.php:

function MyThemesName_preprocess_node(&$vars, $hook) {

Great, now we are good to go.

Print a class if the node has the term XYZ attached

Did you know you can dip into the node object and pull out anything, like a magician with his hat? We can perform the same magic, but we not pulling rabbits, but rather taxonomy terms.

We're going to check if a term is attached, and if so add it to an array, which we will then implode into a concatenated string of class names - cool eh?

function MyThemesName_preprocess_node(&$vars, $hook) {
// first check to see if there are any terms at all, no point running this if not.
if ($vars['node']->taxonomy) {
// declare an array.
$node_term_classes = array();
// check if the node has the term with the id of 10 attached.
if ($vars['node']->taxonomy[10]) {
// if so print a class, notice the safe_string function is cleaning up the term.
$node_term_classes[] = 'node-term-'. safe_string($vars['node']->taxonomy[10]->name);
// implode the array into a new variable
$vars['node_term_classes'] = implode(' ', $node_term_classes); // Concatenate with spaces.

Wicked - now if the node has the term with the id 10, and lets say that is "Photoshop Tips", we can now print a class in node.tpl.php that will be "node-term-photoshop-tips".

You can just keep adding those if conditions for each taxonomy term you want to check on. Simple eh?

But how do we get this into node.tpl.php? Easy, just print the variable:

<!-- node.tpl.php -->
<div class="<?php print $node_term_classes; ?>">
  ...other node code we don't need to see right now...
</div> <!-- /node -->

And thats it people.

Last updated 28th July, 2009 - 12:48am

Authored by Jeff Burnz on