I was curious if it's possible and/or relatively simple to adjust the following piece of code on the page.tpl.php template to pull an image from a field on the current node as the background image, else fall back on the home-bg.jpg and the content-bg.jpg.

<?php if($is_front): ?>
                <img id="main-image" src="<?php print $base_path . $directory; ?>/images/home-bg.jpg" alt="<?php print $site_name; ?>" />
              <?php else: ?>
                <img id="content-image" src="<?php print $base_path . $directory; ?>/images/content-bg.jpg" alt="<?php print $site_name; ?>" />
              <?php endif; ?>

What I would like to do, if it is possible, is create a field called field_bgimage assign it to all content types. Then have the page.tpl.php file check the current node to see if the field_bgimage is populated and if so, display that image as the page background instead of the two fallback images currently reflected in the code above. Does anyone know if this is even possible?

Comments

ishmael-sanchez’s picture

Assigned: Unassigned » ishmael-sanchez
Category: feature » support
ishmael-sanchez’s picture

Title: Can the page file pull the background image from a field on the nodes? » Can you show a field from a node on a page template?
Status: Active » Fixed

>possible and/or relatively simple to adjust the following piece of code on the...
Depends what you consider relatively simple. Anyway, you will need to create the image field, add an image style (unless you want to size the images yourself manually), refine the page preprocess function in template.php to output a custom variable, then output that variable in the page.tpl.php.

// code for your preprocess_page function
function earthish_preprocess_page(&$vars) {
  	// Make sure we are actually on a node page first
    // You could also filter by content type if you wanted
	if (!empty($vars['node'])) {
		// Convenience variable
		$node = $vars['node'];

		// Don't bother if there isn't a file uploaded
		if (isset($node->field_image)) {
				// Render the image as a variable in the page template
				$vars['custom_bg'] = theme_image_style(array('path' => $node->field_image['und']['0']['uri'], 'style_name' => '1250x700'));
    } else {
      // Set a default image if there isn't one
      // If you use theme_image_style the image has to live in the files directory
      $vars['custom_bg'] = theme_image_style(array('path' => 'public://default-bg.png', 'style_name' => '1250x700'));
    }
	}
}
// Around line 168 of the page template update the if statement to this:
<?php print $custom_bg; ?>

>current node to see if the field_bgimage is populated and if so...
In my example I set fallback if there isn't anything uploaded and my field name is field_image.

Also, I changed the title in hopes that more people find this post as it's something I think some advanced themers will want to do.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.