Skip to content Skip to navigation

Random Images from an Image Field in a Block in Drupal 7

« previous next »

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 "Filters" add a "Node" filter, selecting "Node: Type" and then set the "Node:Type" filter settings to "Is one of" and the node type(s) you want to use are selected.
  • Add a "Fields" filter and chose "Fields: [your field name] - value" and set the operator for the fields filter to "is not empty (NOT NULL)"

2. Add a "Block" display type (select "Block" fromt the drop-down above the "Add display" button and click the button.

  • Under "Block settings" set "Caching" to "Do not cache"

3. While still viewing the "Block" display settings, click the "Theme: Information" link in the "Style settings" - look for the very last theme-hint which should be in the format, "views-view-field--[view-machine-name]--[block-machine-name]--entity-id.tpl.php  ...for example if your view's machine name is "random_image_view" and the block is "homepage_feature_block" the theme hint would be "views-view-field--random-image-view--homepage-feature-block--entity-id.tpl.php"
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;">&nbsp;</div>
    But what you do with it depends entirely on your design.

The last thing you want to do, of course, is set up a block to display your view's block. I'll assume you know how to do that.

Facebook Comments