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...


  • I'm sure it is possible. How are these URL's added? Pasted into the post body?
    – s_ha_dum
    Commented Dec 29, 2013 at 23:08
  • They're added into the post body via the WordPress Insert Media button with the link set to Custom URL.
    – David
    Commented Dec 30, 2013 at 0:11

1 Answer 1


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


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;
  • This is probably going to be the only non-jQuery solution. The problem is the images in the site don't have captions. If I'm correct, WordPress simply inserts the image HTML into the post unless a caption is entered. I don't know if any solution would work retroactively, short of a script that does a find-and-replace on document.ready.
    – David
    Commented Dec 30, 2013 at 14:39
  • right, it's not going to work if a caption doesn't already exist. What about filtering the_content?
    – Will
    Commented Dec 30, 2013 at 14:41

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.