wolffer-east's answer satisfies the original question goals of:
- Printing a field
- Doing it in a single file (so everything is in one
place).
However, the code is quite complex for a node.tpl.php file which are only supposed to contain simple PHP statements.
So in the end, I reworked it as follows. In my template PHP file, I put the following:
function print_field($field_name) {
if (arg(0) == 'node' && is_numeric(arg(1))) {
// Get the nid
$nid = arg(1);
// Load the node if you need to
$node = node_load($nid);
}
$field= field_get_items('node', $node, $field_name);
print $field[0]['value'];
}
This is the same as wolffer-east, except it loads the node.
In my node file, I can then use the following:
<?php print_field('field_body_text') ?>
This renders out the field without any labels and HTML, but still clean.
A more advance version is this:
In template.php
function print_field($field_name, $format = 'safevalue') {
if (arg(0) == 'node' && is_numeric(arg(1))) {
// Get the nid
$nid = arg(1);
// Load the node if you need to
$node = node_load($nid);
}
$field= field_get_items('node', $node, $field_name);
if ($format = 'url') {
print file_create_url($field[0]['uri']);
} else {
print $field[0][$format];
}
}
In node.tpl.php
You can swap 'filename' with any of the following:
- value: Prints field without any extra HTML for paragraphs and line
breaks
- safe_value: Prints field HTML for paragraphs and line breaks
- filename: Prints field's filename uri: Prints field's path in
public:// format[*]
- url: Prints field's path in traditional URL format[*]
- alt: Prints field's alt value[*]
- title: Prints field's title value[*]
- width: Prints field's width value[*]
- height: Prints field's height value[*]
[*] only applies to fields that have files/images
The only downside is that it displays the following error message:
Notice: Undefined index: safevalue in print_field() (line 16 of template.php)
I am not sure how to fix this error message, but I guess it is a separate question.