Written by gerard on Saturday 2 May 2009
Drupal's default way of displaying categories really bugs me. They compile all the categories into an unordered list, which adds a lot of pointless complexity to the theme.
Coming from the WordPress school, I'd much prefer to have a comma-separated list of categories. Well, after an epic battle with my node.tpl.php file and much searching on the Interwebs, I've come up with a solution. It's based heavily on a code snippet used in this Lullabot article.
Essentially, what we need to do is parse through all the terms, build a link for each taxonomy term and then use the implode function to build the comma separated list. Here's a sample of the code I'm using:
<?php
<?php
$term_links = array();
// "implode" makes the terms comma-separated
foreach ($node->taxonomy as $term) {
$term_links[] = l($term->name, 'taxonomy/term/' . $term->tid);
}
print implode(', ', $term_links);
?>
?>I'm currently using this directly in the node.tpl.php, but what I'd really like to do is wrap this in a function and place it in the template.php file so that I can redistribute it with my theme when I make it available. And so that I can carry it across to other themes I might design.
Any hints or tips along those lines would be greatly appreciated!
Comments
Moving the code to
Moving the code to template.php is easy.
In template.php your (modified) code:
<code>
function phptemplate_preprocess_node(&$vars) {
// Taxonomy hook to show comma separated terms
if (module_exists('taxonomy')) {
$term_links = array();
foreach ($vars['node']->taxonomy as $term) {
$term_links[] = l($term->name, 'taxonomy/term/' . $term->tid);
}
$vars['node_terms'] = implode(', ', $term_links);
}
}
</code>
In the node template (node.tpl.php and what have you):
<code>
[?php if ($terms) { ?]
[div class="tags"]
[span][?php print t('Tags'); ?]:[/span] [?php print $node_terms; ?]
[/div]
[?php } ?]
</code>
(I replaced the angled brackets, not sure if they would display otherwise.)
Another great code snippet I just found here: http://www.kobashicomputing.com/creating-a-comma-delimited-taxonomy-list...
Stephan Planken
PS: (1) your CAPTCHAs are extermely difficult, and (2) I had difficulty entering this code in your editor.
As a matter of fact, change
As a matter of fact, change the code to include a title:
$term_links[] = l($term->name, 'taxonomy/term/' . $term->tid, array(
'attributes' => array(
'title' => $term->description
)
)
);
Greate example, this was the
Greate example, this was the solution I was looking for when taxonomy_vtn took over my node links.
Cheers!
Hey thanks guys, very helpful
Hey thanks guys, very helpful snippet. Easy to do with views, but not with taxonomy terms it seems.
Post new comment