0

I am not a programmer.

However, I need to know how to use css to add a caption for an image field in a node.

2
  • how are you generating your image html/css in the first place?
    – Jimajamma
    Jul 10, 2012 at 15:01
  • image field in a node
    – hollyh
    Jul 10, 2012 at 17:33

1 Answer 1

3

One way would be to create your own theme_image() in your theme's template.php file. It would be pretty straightforward, just grab drupal's default theme_image() from theme.inc and add a span to it:

If Drupal 6:

function YOURTHEMENAME_image($path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
  if (!$getsize || (is_file($path) && (list($width, $height, $type, $image_attributes) = @getimagesize($path)))) {
    $attributes = drupal_attributes($attributes);
    $url = (url($path) == $path) ? $path : (base_path() . $path);
    return '<img src="'. check_url($url) .'" alt="'. check_plain($alt) .'" title="'. check_plain($title) .'" '. (isset($image_attributes) ? $image_attributes : '') . $attributes .' /><span class="caption">' . check_plain($title) . '</span>';
  }
}

If Drupal 7:

function YOURTHEMENAME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' /><span class="caption">' . (isset($variables['title']) ? $variables['title'] : '') . '</span>';
}

Clear caches/theme registry and now every image will have a span with class caption after it with the image's title in it (or blank if none obviously). If you want to get fancier with wrappers and so forth, just put whatever html you want/need in the return's above.

Then CSS this however you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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