I was trying to find a way to delete the media files attached to all WordPress posts when deleting a bunch of posts at once. I did not want to leave behind a bunch of media files once I got rid of the posts. Turns out there is a way to do this but you have to add some code to your functions.php file. Below is the code to add to functions.php. Be sure to delete this when you are done.


function delete_post_attachments($post_id) {
    global $wpdb;
 
    $sql = "SELECT ID FROM {$wpdb->posts} ";
    $sql .= " WHERE post_parent = $post_id ";
    $sql .= " AND post_type = 'attachment'";
 
    $ids = $wpdb->get_col($sql);
 
    foreach ( $ids as $id ) {
        wp_delete_attachment($id);
    }
}
add_action('delete_post', 'delete_post_attachments');

Leave a Reply

Get in Touch

Please fill out the form below and we will get back to you ASAP

  • This field is for validation purposes and should be left unchanged.