Drupal 7 how to render custom field

19,301

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>
Share:
19,301
martincho
Author by

martincho

Developer and co-founder at sophilabs

Updated on June 24, 2022

Comments

  • martincho
    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
    martincho over 12 years
    Thanks! 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
    Jasmo over 11 years
    You wouldn't need $vars['my_header'] in page.tpl.php in that case, just $my_header is enough.
  • Drake Guan
    Drake Guan over 10 years
    Thanks for this simple but effective answer.
  • cwiggo
    cwiggo about 8 years
    Absolutely blown my mind. This is such a good feature of drupal. Thanks for a great answer.