I'm using the wp dropzone plugin trying to tweak things a little to create a a front end image uploader that sets the current post as the attachments parent.
The plugin as is works really well but by default no matter where I locate the uploader any attachments are marked as un attached in my media library.
I can't for the life of me work out why this isn't working as I've tried all standard calls to get the current post id and set this as the parent.
The full php plugin file is quite extensive so I've included the core section which operates the attachment insertion. See my progress what I have below.
Importantly if I set the post parent as the actual id number; '240' for example it attaches to the called post. I'm looking to attach this to the current post.
/**
* Handle ajax file upload to media library.
*
* @since 1.0.0
*/
function wpday_dz_ajax_upload_handle() {
if (!empty($_FILES) && wp_verify_nonce($_REQUEST['wpday_dz_nonce'], 'wpday_dz_protect')) {
// Including file library if not exist
if (!function_exists('wp_handle_upload')) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
// Uploading file to server
$movefile = wp_handle_upload($_FILES['file'], ['test_form' => false]);
// If uploading success & No error
if ($movefile && !isset($movefile['error'])) {
$filename = $movefile['file'];
$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_parent' => $post->ID,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
// Adding file to media
$attachment_id = wp_insert_attachment($attachment, $filename);
// If attachment success
if ($attach_id) {
require_once ABSPATH . 'wp-admin/includes/image.php';
// Updating attachment metadata
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
}
$message['error'] = 'false';
$message['data'] = wp_get_attachment_url($attach_id);
} else {
$message['error'] = 'true';
$message['data'] = $movefile['error'];
}
wp_send_json($message);
}
}
add_action('wp_ajax_wpday_dz', 'wpday_dz_ajax_upload_handle');
add_action('wp_ajax_nopriv_wpday_dz', 'wpday_dz_ajax_upload_handle');
EDIT:
Have tried:
$id = get_the_ID();
// If uploading success & No error
if ($movefile && !isset($movefile['error'])) {
$filename = $movefile['file'];
$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_parent' => $id,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
Still returns unattached