I need to add a conditional code in a my_theme_preprocess_page function.

The conditional should be like:

if the loaded node has a field called background_image and the value for this field is not empty, then is true


I think this will work for you. Note:

  • It doesn't check the node type.
  • It adds the variable has_background_image on any page that has $vars['node'] available in hook_preprocess_page, and only on those pages.
  • $has_background_image will be true if the field isn't empty (that's the only check).


function MYMODULE_preprocess_page(&$vars) {

  $field_name = 'field_background_image';

  if (!empty($vars['node'])) {

    $node = $vars['node'];
    $items = field_get_items('node', $node, $field_name);

    $vars['has_background_image'] = $items ? TRUE : FALSE;
| improve this answer | |

It's not really clear what do you want to do exactly, but I suppose you want to pass it as another variable.

function my_theme_preprocess_page(&$vars) {
  // Make sure node object exists
  if (isset($vars['node'])) {
    if (isset($vars['node']->field_background_image[0]['uri'])) {
      $vars['has_background_image'] = true;
    } else {
      $vars['has_background_image'] = false;

And then in your page.tpl.php you could use $has_background_image to check if the value is true/false.

If this is not what you asked, edit your question to make your goal clear.

| improve this answer | |
  • 1
    I think this will set $has_background_image to true when the field's attached but empty. – Andy Jul 30 '12 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.