0

I am unable to delete attached files from their folders programmatically or even through the wordpress admin as the admin user. The attachment record deletes from the database but the file remains in the folder.

I can retrieve that file successfully using

get_attached_media( 'application', $post_id )

I can delete the record using

wp_delete_attachment($post_id, true)

But this doesn't delete the file. I tried feeding the confirmed path of the file to wp_delete_file(), no luck

I tried to manually unlink

function delete_unattached_attachments($id){
    $attachments = get_posts( array(
    'post_type' => 'attachment',                        
    'numberposts' => -1, 
    'post_parent' => $id,
        ));                                 
        if ($attachments) {             
            foreach ($attachments as $attachmentID){
                $attachment_path = get_attached_file( $attachmentID->ID); 
                //Delete attachment from database only, not file
                $delete_attachment = wp_delete_attachment($attachmentID->ID, true);
                //Delete attachment file from disk
                $delete_file = unlink($attachment_path);                    
            }                   
        }               
}

I thought it was a capability at first but the admin can't even do it. I've tested on both localhost and live. Same deal. I check the read/write of the folder and I have delete priv.

The folders are json I add as application files for each post to hold chunks of data. I add them like so and they show correct parent in database.

$attachment = array(
    'guid'=> $wp_upload_dir['url'] .'/'. basename( $file ), 
    'post_mime_type' => 'application/json',
    'post_title' => $postTitle,
    'post_content' => $postTitle,
    'post_status' => 'inherit'
);
wp_insert_attachment($attachment, $file, $post_id);

Also the post parent of the attachment is a custom post type

  • there is a typo here: $delete_attachment = wp_delete_attachment($attachmentID->, true); – Cornel Raiu Dec 28 '19 at 23:34
  • you should try to use get_attached_file( $attachmentID->ID, true ) like this to make sure no filters are applied to the get_attached_file and that the path to the file is correct developer.wordpress.org/reference/functions/get_attached_file – Cornel Raiu Dec 28 '19 at 23:41
  • Ok I see the problem. It's returning a path without the sub-directory inside uploads. So uploads/example.json instead of uploads/12/example.json. How do I fix that? – Leopold Dec 29 '19 at 0:22
  • what WP version are you using? – Cornel Raiu Dec 29 '19 at 2:05
  • 5.3.2. Also I tried manual path to a file with the added upload subdir's and it worked so now I just need the right way to get the path – Leopold Dec 29 '19 at 2:27

Your Answer

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

Browse other questions tagged or ask your own question.