Every post on my Wordpress site contains at least one image (in the content, not as an attachment). Each post also contains a custom field with a URL.

I'd like to programmatically modify all posts such that all <img /> tags within the post are wrapped with an anchor tag, pointing to the URL in that post's custom field.

I realize that this would be trivial with JavaScript, but I'd really prefer to do it at the PHP level if at all possible.


EDIT: This is what I've been trying to mess around with, but I don't know WordPress well enough to know if this is the best strategy.

function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
  if ( preg_match('/(<img.*\/>)/', $html) )
    $url = get_post_meta( $id, 'URL', true );
    $html = '<a href="' . $url . '">' . $html . '</a>';
  return $html;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.