Post

Removing Images from a WordPress Post

Today I ran across a unique need to remove images from a WordPress post in a specific post loop.  Because there is no way to do a read more excerpt while taking strict control of the raw content from the_content() I was limited to capturing and manipulating the content from PHP's output buffer.  My solution: obtain the output from the_content() and remove the image tags from the post using preg_replace().

Here is the solution:

1
2
3
4
5
6
7
<?php
   ob_start();
   the_content('Read the full post',true);
   $postOutput = preg_replace('/<img[^>]+./','', ob_get_contents());
   ob_end_clean();
   echo $postOutput;
?>

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

This post is licensed under CC BY 4.0 by the author.