Reputation: 121
So I am submitting new custom posts through a front end form which includes an upload option for the featured image. Everything works as intended from start to finish. But, while inside the 'Edit Post' screen in Wordpress admin dashboard, the featured image thumbnail overflows and appears above the 'Featured Image' tab. Kind of behaves like an 'absolute positioned' element.
Screenshot of what I mean: https://ibb.co/qsmKV6d
No CSS has been added by me yet so it's not that.
This is how I am uploading the image:
$uploaddir = wp_upload_dir();
$file = $_FILES['post-image']['name'];
$temp = $_FILES['post-image']['tmp_name'];
$uploadfile = $uploaddir['path'] . '/' . basename( $file );
move_uploaded_file( $temp , $uploadfile );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'menu_order' => $_i + 1000
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
set_post_thumbnail( $post_id, $attach_id );
What to do? Thanks.
Upvotes: 0
Views: 209
Reputation: 15620
Actually, there's a WordPress function for creating attachment via standard file upload form: media_handle_upload()
— see an example here, and with that function, your code would be simpler. :)
However, to answer the question, the issue happened because you did not generate and update the necessary attachment metadata like file
, width
, height
and the attachment sub-sizes (i.e. intermediate sizes like medium
and thumbnail
).
So to fix the issue, you should call wp_generate_attachment_metadata()
and wp_update_attachment_metadata()
after you called wp_insert_attachment()
:
// Create an attachment post for the image.
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
// Then after that, generate and update the attachment metadata.
$metadata = wp_generate_attachment_metadata( $attach_id, $uploadfile );
wp_update_attachment_metadata( $attach_id, $metadata );
Upvotes: 1