How to remove Images and Videos from WordPress Content

Recently one of my colleague asked to remove all the Images and Videos from the WordPress Content. For this you need to use Filter function in WordPress. Usually we can call this as a Content Filter. add_filter( ‘the_content’, ‘filter_function_name’ ). For the filter function name you should use a unique function name and it cannot be duplicate with any other. If you experiencing to use a prefix for function definitions, that would be more better. As well the main thing you should keep in mind is return the filtered content. Otherwise blank page will be shown to the site users and if there are plugins using the same filter will cause for some errors.

Please refer to the code below. I have define my function name with my web site prefix “nerodev”. It is a good practice to follow in WordPress development. I always this practice in coding. So, always try to use a prefix for your website or with the one you’re working. I have given the 20 as priority. You can change this to anything you want. But WordPress recommended/default for filters is 10.

// Filter Content to remove images & Videos
function nerodev_remove_media_content( $content ) {
   $nero_output = preg_replace("/<img[^>]+\>|<video[^>]+\>/i", " ", $content);
   return $nero_output;
add_filter( 'the_content', 'nerodev_remove_media_content', 20 );

Function Definition

nerodev_remove_media_content( $content ) this is the function we are using to filter the content. With this I am calling to the content into the function. Next I have use a preg_replace to filter the Images and Videos from the content. I do replace both contents with the empty string from the content. preg_replace has three parameters.

  1. Pregmatch code to find Images and Videos in the content.
  2. What is the replace value. Here I am using empty string. Because we need to remove both Images and Videos from the content
  3. Which we are using to apply the filter. Here we are filtering the content.

$nero_output getting the filtered output. By returning the $nero_content it is appending to the content. Now you can see the front and your Images and Videos has been filtered from the content. This way you can filter Images and Videos from the WordPress Content. You just need to change/re-write the pregmatch if you willing to have different output. But main idea is filtering the content.

Hope you enjoy this article.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *