Front-end media uploads in WordPress
Posted in: WordPress
/*
Member image uploads on front-end
Source http://goldenapplesdesign.com/2010/07/03/front-end-file-uploads-in-wordpress/
*/
function banana__insert_attachment($file_handler, $post_id, $field_key = 'false') {
// check to make sure it is a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload($file_handler, $post_id);
if (isset($attach_id) && !is_wp_error($attach_id)) {
if ($field_key) update_field($field_key, $attach_id, $post_id);
return $attach_id;
}
}
Set a featured image
$newupload = banana__insert_attachment($file, 0);
if ($newupload) {
set_post_thumbnail($post_id, $newupload);
}
Attach an upload to a custom field
$newupload = banana__insert_attachment($file, 0);
if ($newupload) {
update_field($field_key, $newupload, $post_id);
}