Using theme overrides

Submitted by Marc on Mon, 05/09/2011 - 5:44pm

As long as I'm being sidetracked and/or feeling inspired to write, here's another quick entry. This one gives a brief introduction to hook_theme and theme overrides.

This particular use case involves changing how CCK's node reference displays its output. I had created a content type that utilized the nodereference field type to attach different stories to a newsletter. So, in this case, I wanted more than just the linked "Title" of the referenced node to appear. Fortunately, CCK is smart/kind enough to make use of hook_theme (in nodereference.module) as follows:
function nodereference_theme() {
return array(
'nodereference_select' => array(
'arguments' => array('element' => NULL),
),
'nodereference_buttons' => array(
'arguments' => array('element' => NULL),
),
'nodereference_autocomplete' => array(
'arguments' => array('element' => NULL),
),
'nodereference_formatter_default' => array(
'arguments' => array('element'),
),
'nodereference_formatter_plain' => array(
'arguments' => array('element'),
),
'nodereference_formatter_full' => array(
'arguments' => array('element'),
'function' => 'theme_nodereference_formatter_full_teaser',
),
'nodereference_formatter_teaser' => array(
'arguments' => array('element'),
'function' => 'theme_nodereference_formatter_full_teaser',
),
);
}

The piece I cared about was the nodereference_formatter_default argument (because I had set the Display for that content type to use the Default). I copied
/**
* Theme function for 'default' nodereference field formatter.
*/
function theme_nodereference_formatter_default($element) {
$output = '';
if (!empty($element['#item']['nid']) && is_numeric($element['#item']['nid']) && ($title = _nodereference_titles($element['#item']['nid']))) {
$output = l($title, 'node/'. $element['#item']['nid']);
}
return $output;
}

from nodereference.module into my template.php file and renamed it mytheme_nodereference_formatter_default (where mytheme is the actual theme name). Then I added a bit of logic after $output = l($title, 'node/'. $element['#item']['nid']); (inside of the if statement) to append some more information to the $output string.

Easy as pie, right? No need to "hack" anything!