Drupal 7 how to render custom field
Solution 1
Don't forget not every page is necessarily a node page so you'd really be better off trying to access this in node.tpl.php
, not page.tpl.php
.
In node.tpl.php
you can render the particular field like this:
echo render($content['field_header']);
hide($content['field_header']); // This line isn't necessary as the field has already been rendered, but I've left it here to show how to hide part of a render array in general.
If you absolutely have to do this in page.tpl.php
then you want to implement a preprocess function in your template file to get the variable you need:
function mymodule_preproces_page(&$vars) {
if ($node = menu_get_object() && $node->type == 'page') {
$view = node_view($node);
$vars['my_header'] = render($view['field_header']);
}
}
Then in page.tpl.php
you'll have access to the variable $my_header
which will contain your full rendered field.
Solution 2
In your node.tpl you have to use following code, for example field name : field_header
<!-- For Showing only custom field's Value Use below code -->
<h2 class="title"><?php print $node->field_header['und']['0']['value'];?></h2>
<!-- ========================= OR ========================= -->
<!-- For Showing custom field Use below code , which shows custom field's value and title-->
<h2 class="title"><?php print render(field_view_field('node', $node, 'field_header')); ?></h2>
<!-- ========================= OR ========================= -->
<h2 class="title"><?php print render($content['field_header']); ?></h2>
Comments
-
martincho almost 2 years
I've added a custom field called 'field_header' to the basic page content type. How do I access this field on the page.tpl.php template so I can display it wherever I want? Ideally I would like to remove it from $content as well. Thanks!
-
martincho over 12 yearsThanks! I needed to place my header in a particular place so I tried your second option, but I couldn't get it to work. Fortunately using the first option (and some jQuery) I was able to solve my problem. I wonder why echo $vars['my_header] didn't work in my page.tpl.php
-
Jasmo over 11 yearsYou wouldn't need $vars['my_header'] in page.tpl.php in that case, just $my_header is enough.
-
Drake Guan over 10 yearsThanks for this simple but effective answer.
-
cwiggo about 8 yearsAbsolutely blown my mind. This is such a good feature of drupal. Thanks for a great answer.