Node taxonomy into classes (full page & teaser)
The snippet shown here will convert node categories to CSS classes. It will do this for each node when viewed as a teaser or when a node is rendered as a full page.
It's up to your own imagination to style it from the 'style.css' file in your theme folder.
Example: node with taxonomy terms (categories) of 'apples', 'oranges' and 'apples & oranges' will put out tax-apples, tax-oranges and tax-apples-oranges for individual nodes.
b-tax-apples, b-tax-oranges and b-tax-apples-oranges will be used for the page body when an individual node is a full page..
Any non-alphanumeric characters and spaces will be stripped and replaced with a '-' so we don't inadvertently have illegal class characters.
Place the code below into your template.php file in your themes folder to pass along the new variable. Create one if it doesn't exist.
Note that you must use module_exist, without the 's' in Drupal 4.7.
<?php
function _phptemplate_variables($hook, $vars) {
if ($hook == 'page') {
$prefix = ' b-tax-';
}
if ($hook == 'node') {
$prefix = ' tax-';
}
if (module_exists('taxonomy') && $vars['node']->nid) {
foreach (taxonomy_node_get_terms($vars['node']->nid) as $term) {
$vars['node_terms'] = $vars['node_terms'] . $prefix . eregi_replace('[^a-z0-9]', '-', $term->name);
}
}
return $vars;
}
?>Inside your page.tpl.php file add this to the <body> class. Use the same $node_terms variable in your node.tpl.php file. Preferably inside a containing div block. The same variable will print out different classes for the two templates.
class="<?php print $node_terms; ?>"With this in place you can now make custom styles, colors , layouts or anything else with CSS according to the categories set for you nodes. The possibilities with this are endless from this simple enhancement.
- Updated to work with the body class
- I'm in the beginning stages of learning this stuff so any improvements are very welcome. The main php snippet came from Dash with some modifications.
- This idea came out of the forum discussion: taxonomy as CSS class?.
