I need to be able to wrap an anchor tag with rel="shadowbox" and href with the path to the image on all img tags that are inserted into the body field of a node. I think I can somehow do this with preprocess?

I realise that I can have a field of images and do it that way, though the client wants the images within the body text itself.

Any advice would be much appreciated.

1 Answer 1


There's a couple different ways one could go about this; I think the most elegant solution could be a text filter.

 * Implements hook_filter_info().
function MODULE_filter_info() {
  $filters = array();

  $filters['shadowbox'] = array(
    'title' => t('Image Shadowbox'),
    'description' => t('Wraps images in anchor tags.'),
    'process callback' => 'MODULE_shadowbox_cb',

  return $filters;

Then, the callback:

 * Image shadowbox callback.
 * @param string $text
 *   The text to be parsed.
 * @param object $filter
 *   The filter, which includes context about which format is being used.
 * @return string
 *   The replaced content.
function MODULE_shadowbox_cb($text, $filter) {
  $ret_val = $text;
  // Logic goes here.
  return $ret_val;

You'll need to enable the filter:

  • /admin/config/content/formats/full_html
  • /admin/config/content/formats/filtered_html

Now, for the content of the callback; you could use a regular expression. https://stackoverflow.com/a/4456866/4619035 is an example for exactly this use case. The downside of regular expressions with HTML is that they're fragile, especially with potentially malformed code. A workaround would be to sequence the filter after anything that cleans up HTML.

Alternatively, use DOM to manipulate the content - https://stackoverflow.com/questions/18316527/php-dom-wrap-image-in-link-and-add-span-before-image-tag describes this approach well.

Your Answer

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

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