How to Remove Images from the_content() but Preserve HTML Formating

remove-img-from-content
When working with WordPress development couple of days ago, I’ve manage a few quick Q&A with some of my colleague with user experience when dealing with WordPress posts. One of most sought out or talked topic was the_content() vs the_excerpt() features in WordPress post formatting.

Using the_excerpt() is great for user to shortened their long posts into 30-50 short text. However it doesn’t let you control where the post length should stop when converting to shorter text. The usual code used when using featured thumbnail with short text were like this:

[php]<?php
the_post_thumbnail(‘thumbnail’, array(‘class’ => ‘alignleft’));
the_excerpt();
?>[/php]

This will end result with:
thumb-with-excerpt

But this is not what user want sometime, they want to add their own ‘read more’ and want to control where to stop the long post and most important part is to preserve the HTML format. So we try this code instead:

[php]<?php
the_post_thumbnail(‘thumbnail’, array(‘class’ => ‘alignleft’));
the_content(‘…read more’);
?>[/php]

This will end result with:
thumb-with-content
This may seem good enough but what if you do not want any images to show from the_content(). Notice the ‘red’ mark i added. This image from the post are not something user want to show in their short text.

In this WordPress Tutorial, I’ll show you how to remove images from the_content() but still preserve the HTML formatting in post. First insert below code into your theme functions.php

[php]if( !function_exists(‘get_the_content_with_format’) ):
function get_the_content_with_format ($more_link_text = ”, $stripteaser = 0, $more_file = ”) {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters(‘the_content’, $content);

// remove captions
$content = preg_replace(‘`\[[^\]]*\]`’,”,$content);
$content = strip_tags($content, ‘<p><a>’);
return $content;
}
endif;[/php]

Notice i only allow HTML tag ‘p’ and ‘a’ when the $content return as the_content().

Now instead of using the_excerpt() and the_content(), we used this code instead:

[php]<?php
the_post_thumbnail(‘thumbnail’, array(‘class’ => ‘alignleft’));
echo get_the_content_with_format($more_link_text = ‘…Read More’);
?>[/php]

Final result will be like this:
strip-img-the-content

That’s about it folks, hope you find this tutorial useful and can help you in your next WordPress development project. Please enjoy and share this tutorial if you like it.

Photo credits to alex barth

Scroll to Top