0

I'm currently trying to upload an image to the WordPress media library programmatically. The problem is, that when I check the media library, there is no thumbnail showing up and the file size is also empty. This is my code:

if ( ! empty( $_FILES ) && is_int( exif_imagetype( $_FILES['file']['tmp_name'] ) ) ) {

    $file = wp_handle_upload( $_FILES['file'], array( 'test_form' => false ) );

    if ( $file && ! isset( $file['error'] ) ) {
        $filename   = $file['file'];
        $attachment = array(
            'post_mime_type' => $file['type'],
            'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
            'post_content'   => '',
            'post_status'    => 'inherit',
            'guid'           => $file['url']
        );

        $attach_id                = wp_insert_attachment( $attachment, $file['url'] );
        $attach_data              = wp_generate_attachment_metadata( $attach_id, $filename );
        $update_attachment_result = wp_update_attachment_metadata( $attach_id, $attach_data );

        if ( $update_attachment_result ) {
            $response = array(
                'attach_id' => $attach_id
            );
            wp_send_json_success( $response, 200 );
            wp_die();
        } else {
            wp_send_json_error( null, 500 );
            wp_die();
        }
    } else {
        wp_send_json_error( null, 500 );
        wp_die();
    }
} else {
    unlink( $_FILES['file']['tmp_name'] );
    wp_send_json_error( null, 500 );
    wp_die();
}

This is an image from the media library of the uploaded image:

enter image description here

When I'm checking the wp-uploads folder, I can see the uploaded images:

enter image description here

Do you have any idea why this happens to me?

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.