Is there a way to bulk remove attachments from WordPress database but not delete the actual files from the server?

Sort of like the opposite of http://wordpress.org/plugins/add-from-server/


Just use a custom $wpdb query, something like

function remove_all_attachments() {
  global $wpdb;
  $ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment'");
  if ( empty($ids) ) return;
  $remove = implode(',', $ids);
  // remove post meta
  $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id IN ({$remove})");
  // remove posts
  $wpdb->query("DELETE FROM $wpdb->posts WHERE ID = IN ({$remove})");

After that just call remove_all_attachments() whatever you want and all your attachemnts posts are gone, but the file stay there...

| improve this answer | |
  • If I use the plugin SQL Executioner, I'd use $wpdb->query("DELETE FROM $wpdb->posts WHERE post_type = 'attachment'"); to run command, is that correct? – ayutheos Oct 22 '13 at 4:24
  • How do I filter attachments named *_small.jpg? – ayutheos Oct 22 '13 at 4:34
  • @ayutheos I've updated the answer to remove also postmeta. regarding your questions: (1) I don't know that plugin. (2) you can add AND guid LIKE '%_small.jpg' to SELECT query, but is not very reliable because guid column is not reliable... a better result involve to get the real image url using WP API, but if you have hundreds of images it can be a serious performance problem – gmazzap Oct 22 '13 at 5:12
  • SQL Executioner is a plugin to run SQL queries from Wordpress. I have about ~300+ manually created thumbnail images that I'd like to remove from the database but not the actual file itself. I'll try out your function in my local install to test it :) – ayutheos Oct 22 '13 at 6:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.