-1

How can I print a field on my template, not only in node page but in every page.

I use this in my page.tpl but it's wrong:

echo $node->field_custom['und'][0]['value']; 

Update

I solved using this code on template.php:

function MyTheme_preprocess_page(&$vars) { $mynode = node_load(1); $vars['field_custom'] = field_get_items('node', $mynode, 'field_custom'); } 

And this in page.tpl:

<?php if (isset($field_custom)) : print $field_custom[0]['value']; endif; ?> 
10
  • What does "it's wrong" mean? Commented Oct 13, 2016 at 12:11
  • The code doesn't work. Commented Oct 13, 2016 at 12:18
  • Are you really not going to try to elaborate? That's all you're prepared to offer in terms of a good question for this repository? Commented Oct 13, 2016 at 12:19
  • I'll close this until you've had a chance to get it up to scratch. See the help center for suggestions, or feel free to open a meta question if you don't understand why "it's wrong" and "doesn't work" aren't acceptable problem statements Commented Oct 13, 2016 at 12:26
  • I've tried some solution but I haven't really figured how to take the filed of single node and print it on my theme. I had to write all the code tried so far? Commented Oct 13, 2016 at 12:29

1 Answer 1

2

Try the following code:

 <?php function THEME_preprocess_page(&$vars) { $vars['field_custom'] = ''; // Get the object and do some other checks based on what you need. if (($node = menu_get_object()) && $node->type) { // Generate a render array for the node. $view = node_view($node); // "Create" a new variable for the page.tpl.php. // This will expose $VAR_NAME in the page template. $vars['field_custom'] = drupal_render($view['field_custom']); } } ?> 

or you can also use:

$vars['field_custom'] = field_get_items('node', $mynode, 'field_custom'); 

Then add this to your page.tpl.php:

<?php if (isset($field_custom)) : print $field_custom; endif; ?> 
2
  • $node is available in the page.tpl.php only if there is some node associated with the page. Check the variables available in page template. Also, node ID will be the second parameter (node/nid) Then you can access using the field_get_items, for example field_get_items('node', $node, 'field_name'); Commented Oct 13, 2016 at 12:38
  • This is good. But print the render field just in the node page. Commented Oct 13, 2016 at 12:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.