Is there a way to delete images from WordPress media library programmatically?

This is a follow-up of my question which did solve my problem, well, a little bit.

I noticed that there are still images on my uploads folder but of different size. Is there a way to delete all traces of the image that I uploaded? It seems that wp_delete_attachment only deletes the image that is “attached” but not the other image sizes that WordPress automatically created.

Read More

I use this function to generate attachment IDs

function insert_attachment( $file_handler, $post_id, $setthumb='false' ) {

    // check to make sure its a successful upload
    if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attach_id = media_handle_upload( $file_handler, $post_id );

    if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);

    return $attach_id;  
}

(I got that from: http://goldenapplesdesign.com/2010/07/03/front-end-file-uploads-in-wordpress/)

I use this for a custom file upload in front-end and not the usual upload using the Media Library. This is for a site that requires user uploads.

Any thoughts?

Related posts

Leave a Reply

1 comment

  1. This can be achieved with wp_delete_attachment( $attachment->ID );

    Here’s an example to delete all attachments related to a post:

    // Delete Attachments from Post ID 25
    $attachments = get_posts(
        array(
            'post_type'      => 'attachment',
            'posts_per_page' => -1,
            'post_status'    => 'any',
            'post_parent'    => 25,
        )
    );
    foreach ( $attachments as $attachment ) {
        wp_delete_attachment( $attachment->ID );
    }