Reading node field values in drupal7 programmatically

jantimon picture jantimon · Feb 21, 2011 · Viewed 9k times · Source

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?

Answer

Berdir picture Berdir · Feb 21, 2011

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.