Removing first image from the_content

I recently had a client want to put the_title below the first image. Without making it to complicated by adding custom fields or anything like that. I thought that I could grab the first image from the content with catch_that_image and then display the title and then display the_content. But if I did it that way, it would display the first image twice. So I had to come up with a way to remove the first image from the_content here comes filters!

// This is the filter that gets added to the content
add_filter( 'the_content', 'remove_first_image' );

// This is the function name
function remove_first_image($content) {
global $post, $posts;

// This is the pre replace that removes the first image
$content = preg_replace('//i',$matches,$post->post_content,1);
return $content;
}

You can see a working example at Barack Obama. The first image is called via catch_that_image and then the_title is displayed and then the_content after that.

This way Casey just keeps doing what he is doing without having to change any of the posts around that he already has done.

About Weston Deboer

I like to use wordpress for any and every website that I work on. No matter how big or how small the website is.
This entry was posted in Wordpress and tagged , , , . Bookmark the permalink.

4 Responses to Removing first image from the_content

  1. MysteryE says:

    Hi!
    I would like to use the code above, but I don’t have any idea where to put it or how to insert it in the single.php or index.php.

    I need more detail to insert that code…

    Thanks before. :)

  2. wpdesigner says:

    Doesn’t work i just tried it on wordpress 2.9.1 :-( would you know how i can grab the first image uploaded into the post and display it using timthumb then remove the duplicate one displayed in the_content () ? i’m a wordpress template designer and i’ve been pulling my hair out trying to figure it out :-( any help is appreciated

  3. Frank says:

    You can use this.

    replcae

    with below

    <?php
    ob_start();
    the_content('Read the full post',true);
    $postOutput = preg_replace('/]+./’,”, ob_get_contents(),1);
    ob_end_clean();
    echo $postOutput;

    ?>

  4. Gabriel says:

    Is there a way to separate the first image and only display that instead of the content?

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>