Search code examples
phpdrupaldrupal-7

Drupal 7 how to render custom field


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!


Solution

  • 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.