Thursday, September 18, 2014

Drupal 7 - Picture - Adding captions to responsive images

I've setup an D7 site (a D6 upgrade) with Picture and Breakpoint where I want to show a caption for some of the images. In the  D6 version used the title attributes as captions for some of the images with a phptemplate_imagecache function. (Depending on the image style used.)

Oh caption, my caption
There are some modules (,,, etc) which give you the possibility of adding a caption field, but as I do not want to build another module to convert all existing title tags to these caption attributes, and also need a solution for non javascript browsers, I needed something more basic.

Based on the specific imagestyle or specific picture mapping, decide to render or not render a caption. The content of the caption is the content of the title attribute.

Add a theme function to your theme's template.php
The idea is to simply override the theming function in picture (which is the module I use for my responsive images)

// this theming function assumes that the picture module is installed
function THEMENAME_picture($variables) {
  // first produce the  standard picture output
  // we only add titles to the images where a specific picture mapping is defined
  if (array_key_exists('breakpoints', $variables) && array_key_exists('title', $variables)){
     if ($variables[breakpoints]['custom.user.normal']['1x'][image_style] =='rsp_adviesplaatjecustom_user_normal_1x'){
        if ($variables['title'] !=''){
           $output=$output.'<div class="image-caption"><div class="image-caption-text">'.$variables['title'].'</div></div>';
  return $output;