WordPress: Remove image from content on post save

October 28, 2012

If you have a post type where you want to allow the user to utilize the built in content box, but you do not want the user to be able to save images there is a quick trick you can use to strip image tags away before the content is saved to the database. This utilizes the powerful WordPress hooks system, the ‘content_save_pre’ filter.

The content_save_pre filter allows you to manipulate the content of the content box prior to save. Using another WordPress function, wp_kses() you can easily strip away tags that are not allowed. Here is the code to set it up

Tap into the hook

add_action( 'content_save_pre', 'remove_images_from_content' );

The first parameter is the WordPress filter. The second is the name of your function to call when the hook runs.

Now the code to strip the image tags

public function removeImagesFromContent( $Content ) {
   global $allowedposttags;
   unset( $allowedposttags['img'] );
   $Content = wp_kses( $Content, $allowedposttags );
   return $Content;
}

If you want to target a specific post type you can do so by tweaking the following

public function removeImagesFromContent( $Content ) {
   global $post, $allowedposttags;

   if( 'TARGETED_POST_TYPE' != $post->post_type ) {
      return $Content;

   unset( $allowedposttags['img'] );
   $Content = wp_kses( $Content, $allowedposttags );
   return $Content;
}