Solved.
For anyone who wants to do this too (useful if you include a gallery with all the post’s images in your template), replace the function handle_file with the following code:
function handle_file($upload_data)
{
$slug = '';
$slug = basename($_SERVER['HTTP_REFERER']);
global $wpdb;
$id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '$slug'");
$return = false;
$uploaded_file = wp_handle_upload($upload_data, array('test_form' => false));
if (isset($uploaded_file['file'])) {
$file_loc = $uploaded_file['file'];
$file_name = basename($upload_data['name']);
$file_type = wp_check_filetype($file_name);
$attachment = array(
'post_mime_type' => $file_type['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($file_name)),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $id
);
$attach_id = wp_insert_attachment($attachment, $file_loc, $id);
$attach_data = wp_generate_attachment_metadata($attach_id, $file_loc);
wp_update_attachment_metadata($attach_id, $attach_data);
$return = array('data' => $attach_data, 'id' => $attach_id);
return $return;
}
return $return;
}
IMPORTANT: your permalinks must end with the post’s slug to make this work.
@paraddictednet, I would like to do this but could you please elaborate on your last statement “permalinks must end with the post’s slug to make this work”. I hope you are talking about pretty permalinks where the posts url are not according the year, month, date… or so but based on actual words in the title.
Another important thing I would like to get help with is, I have a frontend post creator form. Do you think this hack could work with the form so the the uploaded images will be attached to the posts. If so please be kind and explain.
Cheers.