Delete/replace img tags in post content for auto published posts [closed]

You can use the function get_posts to get all your post, and then use a foreach cycle to replace the img tags using the regex you posted and then use wp_update_post to change post content:

function remove_images_form_past_posts() {    
  if ( get_transient('images_removed_from_past') ) return;
  $posts = get_posts('nopaging=1');    
  if ( $posts ) {
    foreach ( $posts as $post ) {
      $newcontent = preg_replace('/<img[^>]+\>/i', '', $post->post_content);
      $newpost = array( 'ID' => $post->ID, 'post_content' => $newcontent);
      wp_update_post($newpost);
    }
    set_transient('images_removed_from_past', 1);
  }
}

add_action('admin_init','remove_images_form_past_posts');

This code should be used only once, to change the past posts content. To ensure it runs only once I’ve used a transient. See Codex for Transient API.

Now you have to add a function that hook into 'wp_insert_post_data' filter hook and prevent new posts are added with images:

function remove_images_before_publish( $data, $postarr ) {
  if ( ! empty($data['post_content']) )
    $data['post_content'] = preg_replace('/<img[^>]+\>/i', '', $data['post_content']);
  return $data;
}
add_filter('wp_insert_post_data','remove_images_before_publish', 20, 2);

Leave a Comment