Removing everything BUT Images in a WordPress Post

A while back I wrote an article on Removing Images from a WordPress Post. Sebastian asked an interesting question; he wanted to remove everything but the images. This is actually pretty straightforward; here is how you do it:

 
.
.
.
<?php
           $beforeEachImage = "<div>";
           $afterEachImage = "</div>";
           preg_match_all("/(<img [^>]*>)/",get_the_content(),$matches,PREG_PATTERN_ORDER);
           for( $i=0; isset($matches[1]) && $i < count($matches[1]); $i++ ) {
                 echo $beforeEachImage . $matches[1][$i] . $afterEachImage;
           }
?>
.
.
.

Keep in mind this code needs to be in the WordPress Loop and you can control what is around each image using the variables beforeEachImage and afterEachImage above.

2 Comments so far »

  1. Removing Images from a WordPress Post | Chris Schuld's Blog said

    November 14 2009 @ 2:03 pm

    [...] EDIT: make sure you check out the updated version of this solution. Also, view my solution for removing everything but the images. [...]

  2. Kris said

    February 8 2010 @ 10:38 am

    Hi Chris,

    This is amazing! Is there a way to put each image into an array? I want to use your other example with this one to create a custom excerpt.

    thanks.

    Kris

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

Email: (Required)

Website:

Comment: