WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to determine if the REGEX I'm using is incorrect -- or if I'm missing something basic here. The following:

function wpdu_image_replace($content) {
    global $post;
    preg_replace( '/<img.*src="(.*?)".*?>/', '<a href="\1">Image file</a>', $post->post_content );

    return $content;

should look for any <img> within post->post_content (the post's content) and replace the entire tag with an href that simply links to the image file. In the end what I'm going to do with this is a bit more complex -- but I figured I'd start with the basics. Any help would be greatly appreciated. Thanks!

share|improve this question
up vote 0 down vote accepted

You use preg_replace function incorrectly. This function returns replaced content:

add_filter( 'the_content', 'wpdu_image_replace' );
function wpdu_image_replace( $content ) {
    return preg_replace( '/<img.*?src="(.*?)".*?>/', '<a href="$1">Image file</a>', $content );

Also pay attention that you don't have to use global variable $post, because content of the post is passed to your function as first argument.

share|improve this answer
'doh, thank ya sir! – Zach Jun 14 '12 at 16:28
@Zach u r welcome – Eugene Manuilov Jun 14 '12 at 18:02

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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