Add Snippet To Project
Sometimes, for various reasons, you might need to remove images embedded within your WordPress post content. Whether it’s because the images are no longer relevant, to decrease your overall page load time, or to revamp your content presentation, removing images can be done efficiently, without the need to manually edit each post. This article is designed to guide you through different methods of achieving this, saving you time and further enhancing your WordPress site management skills.
function wpturbo_remove_images_from_post_content($content) {
$postWithoutImages = preg_replace('/<img[^>]+>/i', '', $content);
return $postWithoutImages;
}
add_filter('the_content', 'wpturbo_remove_images_from_post_content');
Here’s an overview of the functionality of each component of this PHP code snippet:
This PHP script starts by defining a function called wpturbo_remove_images_from_post_content()
. This function’s purpose is to remove image tags from the content of posts on your WordPress website. The function has one parameter, $content
.
function wpturbo_remove_images_from_post_content($content) {
Inside the function, we apply a preg_replace
function to the $content
, which is the content of the post. The parameters within the preg_replace
function make use of regular expressions to find and replace specific content — in this case, an image tag.
$postWithoutImages = preg_replace('/<img[^>]+>/i', '', $content);
The /
characters are delimiters, which indicate the start and end of the pattern. <img[^>]+>
is the pattern we’re checking for. In specific:
<img
checks for the start of an image tag.[^>]+>
checks for one or more characters that are not>
(the end of an HTML tag).
This pattern will match any image tag, regardless of the attributes the tag might contain. The i
after the final delimiter makes the pattern case-insensitive, allowing it to match image tags regardless of whether they’re written in upper case, lower case, or a mix.
The second parameter of preg_replace
function is ''
— an empty string. This means every image tag that’s matched will be replaced with no content, effectively removing it from the post.
Finally, the function ends by returning the post content, which now should have all image tags removed.
return $postWithoutImages;
}
As the last action, the newly created wpturbo_remove_images_from_post_content()
function is hooked to the WordPress filter hook 'the_content'
. This binds our custom function to the WordPress core process that generates the HTML content for posts and pages, ensuring our function’s actions will be applied to the body of every post or page on the website.
add_filter('the_content', 'wpturbo_remove_images_from_post_content');
In conclusion, placing this script in your WordPress theme’s functions.php
file will ensure that all posts’ content doesn’t contain image tags.