Support

Account

Home Forums Front-end Issues Delete Uploaded Files From Media Library

Helping

Delete Uploaded Files From Media Library

  • Hello!

    I have a front-end form that allows my users to upload files, however, when the user deletes a file it remains in the media library. I want to make it so when a user decides to delete the file, to permanently remove it from the media library too.

    Here is the code I tried but it doesn’t work:

    function wpse_83587_delete_file( $value, $post_id, $field  ) {
        $old_value = get_field( $field['upload_my_file'], $post_id, false /* Don't format the value, we want the raw ID */ );
    
        if ( $old_value && ( int ) $old_value !== ( int ) $value )
            wp_delete_file( $old_value, true );
    
        return $value;
    }
    
    add_filter( 'acf/update_value/type=file', 'wpse_83587_delete_file', 10, 3 );
  • Hi @tatimenabi

    If $old_value returns a file URL, you could look to use attachment_url_to_postid()

    Once you have the attachment ID, you can then use wp_delete_attachment()

    Something like this:

    <?php
    function wpse_83587_delete_file( $value, $post_id, $field  ) {
        $old_value = get_field( $field['upload_my_file'], $post_id, false /* Don't format the value, we want the raw ID */ );
    
        if ( $old_value ){
    		
    		$attachment_id = attachment_url_to_postid( $old_value['url'] );
    		wp_delete_attachment( $attachment_id, 'true' );
    	}
    
     
    }
    
    add_filter( 'acf/update_value/type=file', 'wpse_83587_delete_file', 10, 3 );

    Code untested but may help!

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.