Reputation: 10250
In WordPress, if a media file is uploaded within the WP admin post edit screen, it will automatically be attached to the current post being edited. However, I'm allowing my site's authors to upload images via the front-end. The upload form I have created is on the post page (within the loop) so I have the post's ID available when uploading the image.
Is there a way to automatically attach the uploaded image to the post? Currently when I visit the Media section in WP admin, all of the images uploaded thus far are marked as 'unattached'.
Ref:
https://codex.wordpress.org/Using_Image_and_File_Attachments#Attachment_to_a_Post
Edit: I should mention I'm using WordPress Liveblog: https://github.com/Automattic/liveblog - images are uploaded when a user pastes an image URL into the form.
Upvotes: 6
Views: 19157
Reputation: 15550
You can run following function after your upload form submission. Let say your upload form is as following:
<form action="your_action.php" method="post"
enctype="multipart/form-data">
<input type="file" name="attachment" />
<input type="hidden" name="post_id" value="<?php global $post; echo $post->ID; ?>" />
</form>
And in your upload handling part:
<?php
$filename = $_FILES["file"]["attachment"];
$post_id = $_POST["post_id"];
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attach_data );
Upvotes: 8