Dynamically adding Captions to images

I have a site where the author has included Amazon Affiliate links. They've done this by adding the URL to product images.

I'm wondering if there's a way to add a function that will automatically add a wp-caption below these images if they're linked to Amazon.

Basically the condition would need to be: if an href containing an image is linked to a domain including 'amazon', add a caption below that image that says "Buy Now". The caption would also have the same link as that image.

I've been able to do this with some hacky jQuery, but it doesn't always fire properly. I think there might be a better way...

Thanks

Topic captions functions images Wordpress

Category Web


The media uploader wraps the image and caption in the [caption] shortcode. There is a filter called img_caption_shortcode that can do what you want. The caption itself is passed as part of an array to the shortcode handler, as is the image id.

add_filter( 'img_caption_shortcode', 'wwm_img_caption_filter', 10, 3 );

function wwm_img_caption_filter( $empty, $attr, $content )
{

  $image_id = $attr['id'];
  //do some checking of the $image_id (attachment id) to see what it links to
  //if it links to amazon, include the link in the caption:
  if ( /*my condition is met*/ ) {

   $attr['caption'] = ;//modify the string appropriately
  }

  return ;//some string - see documentation
}

Here's some documentation on the filter: http://codex.wordpress.org/Plugin_API/Filter_Reference/img_caption_shortcode

UPDATE **

if the image in question doesn't have a caption already use the_content filter

add_filter( 'the_content', 'add_affiliate_link_caption' );

function add_affiliate_link_caption( $content )
{

 //I'm not even going to try a regex...
 //but some sort of regex find/replace stuff on $content

 return $content;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.