Many themes these days have a tendency to prominently feature the featured image of a post. This is good. They are fulfilling their purpose. However, during development of the Pressgram plugin, I came to find that there was a demand, especially in the realm of photoblogging, to strip the image from the post content in favor of allowing the theme to prominently display the image. The post content, then, would serve only as a caption, or supplement, for the featured image.

Currently, the Pressgram plugin has an option to strip the first image from a post. I don’t think this is the ideal solution for handling post content. For what happens some day when the theme is switched to one that would be better served by the image residing in the post content? It would be a laborious task to re-insert every image.

So, how can this be handled? If you visit the photo archive on this site, you will notice that featured images are displayed alongside the text content of each photograph post. However, if you enter a single photo post, you will see the images still present in the actual post content. Here, the theme does nothing with the featured image.

Single posts showing full content … the archive loop stripping images … how can this be done? The easy way would be to add some simple css styling, hiding post images when on the archive page. .entry-content img {display:none;}

This works. Unfortunately, images are still served to the browser, slowing the page’s load time.

A better solution is to dynamically strip the images from the post content after it has been queried from the database and before it is served to the browser. And so, I am employing the following function:

function uamv_strip_images( $content, $placeholder = '' ) {
    return preg_replace( '/(<a[^>]*>)*<img[^>]*>(</a>)*/sim', $placeholder, $content );

Then, whether you identify photo posts via an image post format or a custom post type, you will be able to properly call this function in your theme. In my case, I post photos as a custom post type of photograph. Thus, I modify content.php to strip images in certain instances:

if ( post_type_archive( 'photograph' ) ) {
    uamv_strip_images( get_the_content() ) );

Now, when the post type archive for photographs is displayed, all images have been removed from post content while keeping the original post content intact.

You will also notice that the function uamv_strip_images also allows for a placeholder to be inserted where images have been stripped. Could be useful in certain situations.

I considered using this approach for the Pressgram plugin, but it would be quite difficult to accommodate the various theme environments, so we will probably forego that change. Hope you might find use for some slick image stripping.

Code on!