Random Images from an Image Field in a Block in Drupal 7
March 24 2011 11:59:55 AM
The Problem:Displaying a random image from the image field in a certain node type (where not every node has an image) in a block.
My Solution:
1. First thing is create a view with the following "Default" settings:
- Under "Basic settings" set the "Use page" setting to "1 item", i.e. "Display a specified number of items" and set that number to "1" with an offset of "0"
- Under "Advanced settings", "Caching" should be set to "None"
- Under "Style Settings", "Style" should be "Unformatted" and "Row style" should be "Fields"
- Under "Fields", set to your image field (in my case this is called "field_image")
- The formatter should be "Image" with an Image style appropriate to your application. Everything else is going to be overridden in a theme-hint that I'll explain further down.
- Under "Block settings" set "Caching" to "Do not cache"
4. Be sure you have saved the view.
5. Create a file in your theme template directory with the name of the theme-hint from above.
- To work with the image URL directly you need to extract it from the view output. Since the view is only displaying one image, this is pretty easy. I used the following code:
preg_match("/src=\"(.+?)\"/i",$output, $matches);
$src = $matches[1]; - Now that you have the URL of the image you can do whatever you want to display it. In my case I made it the background of a div that filled the block, like so:
<div id="featured-bgimage" style="background: #ddd1a4 url('<?php echo $src; ?>') repeat-x center top;"> </div>
But what you do with it depends entirely on your design.
- Comments [0]