Home > Mobile >  Wordpress: how to upload image to media library from a form?
Wordpress: how to upload image to media library from a form?

Time:08-24

Struggling to upload image to media library from form, I don't think I'm fully understanding the function. With my current code I'm successfully uploading file with file name, file type and author, but the file size and the file itself (the content) is not uploaded.

Current code:

if (isset($_POST['settings-submit'])) {
                        
   $file = $_FILES['settings-upload-image'];

   $file_name = sanitize_file_name($file['name']);
   $file_type = $file['type'];

   $args = array(
     'guid' => $file['url'], // just realized that this doesn't even exist in my array
     'post_title' => $file_name,
     'post_mime_type' => $file_type,
    );

    wp_insert_attachment($args, $file_name);
                    
}  

Ignoring validation for now. Possibly I'm not even using the right function?

CodePudding user response:

Try to remove everything after line $file_type = $file['type']; and put this code instead:

// first checking if tmp_name is not empty
if (!empty($file['tmp_name'])) {
    // if not, then try creating a file on disk
    $upload = wp_upload_bits($file_name, null, file_get_contents($file['tmp_name']));

    // if wp does not return a file creation error
    if ($upload['error'] === false) {
        // then you can create an attachment
        $attachment = array(
            'post_mime_type' => $upload['type'],
            'post_title' => $file_name,
            'post_content' => '',
            'post_status' => 'inherit'
        );

        // creating an attachment in db and saving its ID to a variable
        $attach_id = wp_insert_attachment($attachment, $upload['file']);

        // generation of attachment metadata
        $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);

        // attaching metadata and creating a thumbnail
        wp_update_attachment_metadata($attach_id, $attach_data);
    }
}

I think this code should easily create a file in the uploads folder and be visible in the media library. I wrote something similar when I was doing an integration with an external site in wordpress and it works for me without any problem.

  • Related