Are you looking for a way to remove all images from the_content
in a post? While there’s probably a plugin for this, we have created a quick code snippet that you can use to remove all images from the the_content
in a post in WordPress.
Instructions:
All you have to do is add this code to your theme’s index.php file:
<?php echo preg_replace('/<img[^>]+./','',get_the_content()); ?>
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: How to create stunning WordPress optin forms and 10 best WordPress testimonial plugins.
You can use the wp_kses for this purporse. Add the filter for the img element using the wp_kses_allowed_html filter.
In your functions.php.
function theme_slug_kses_allowed_html($tags, $context) {
switch($context) {
case ‘no-images’:
$tags = wp_kses_allowed_html(‘post’);
unset( $tags[‘img’] );
return $tags;
default:
return $tags;
}
}
add_filter( ‘wp_kses_allowed_html’, ‘theme_slug_kses_allowed_html’, 10, 2);
Then in index.php.
echo wp_kses( get_the_content(), ‘no-images’ );
Can this be wrapped up in a function?
It certainly could be in theory, but this may be a bit overkill for one line of code.
Looks fantastic and Thank you!
In my case I need to keep the “featured image” and strip all images from all post bodies.
Is that what this snippet will do?
If the theme is using the featured image, then yes, the featured image should remain and the images should be removed. Note that you may want to make a backup before running a snippet like this.
How about Image in WP-CAPTION? That I mean hide the text on WP Caption too.
How to hide it?
This would sadly need more advanced pattern matching.
what if i want the image to show up but be linked to the post instead of the image itself?
thats what i was searching for! thank you.
Nice!!! thanks
very useful. thanks
No problem glad that I could help!