Support » Developing with WordPress » Image uploaded from front not getting attached to Featured Image
Image uploaded from front not getting attached to Featured Image
-
Hello,
I am trying to upload image from frontend and once form submitted, I need to save that image as an “Featured Image” for that post.
$upload_dir = wp_upload_dir(); // Set upload folder $upload = wp_upload_bits($edit_doc_image, null, file_get_contents($edit_doc_image)); $filename = $upload['file']; // Check folder permission and define file location if (wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } $image_data = file_get_contents($upload['url']); // Create the image file on the server. file_put_contents($file, $image_data); $wp_filetype = wp_check_filetype($filename, null); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment($attachment, $filename, $pid); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata($attach_id, $filename); wp_update_attachment_metadata($attach_id, $attach_data); $image = set_post_thumbnail($pid, $attach_id);
Here images are getting uploaded in uploads/2018/08 folder but size displays as 0 bytes. When checked for file type, in folder, it displays as plain text. Even I checked for file type to pass it in post_mime_type, it shows proper.
Admin : https://prnt.sc/kh7csr
Folder : https://prnt.sc/kh7foxAny help in this will be highly appreciated. Thanks in advance.
-
If you use the “file” input form field type, when the form is submitted, the file is automatically uploaded to PHP’s temp directory. You can then use media_handle_upload() to move the file to uploads and create the attachment file.
.
- You must be logged in to reply to this topic.