Reading node field values in drupal7 programmatically

9.4k views Asked by At

I am looking for the best way to get a field value from a node id.

My actually code works however I guess there is an easier way.

$node = node_load( 1 );
$lang = $node->language;
$field = 'body';
$value = '';

if ( isset($node->{$field}[$lang]) && isset($node->{$field}[$lang][0]) )
{
  $value = $node->{$field}[$lang][0]['value'];
}

echo $value;

Is there any build in drupal function that takes care of this?

2

There are 2 answers

0
Berdir On BEST ANSWER

Not all of it, but you should be able to simplify it a bit with http://api.drupal.org/api/drupal/modules--field--field.module/function/field_get_items/7.

You still need to check if $items[0] exists and get the 'value' of that.

0
Druvision On

Thanks @Berdir. I agree field_get_items is a better way. Here is a code example:

<?php
  $body = field_get_items('node',$node, 'body');
  print $body[0]['value'];
?>