I want to post attachments from the front end in WordPress, here is my code which works:
Form process:
global $post;
if ( $_FILES ) {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,0);
}
}
}
}
Function to process uploads:
function insert_attachment($file_handler,$post_id,$setthumb='false') {
// check to make sure its 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 ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
I would like to set the post_author
of the attachment, as currently is defaults to the current logged in user.
I have tried adding the following into the function, but it doesn’t seem to work:
$my_post = array(
'ID' => $attach_id,
'post_author' => 2
);
wp_update_post( $my_post );
Not quite sure what had happened, i retried this and seemed to of worked! Just wanted to update incase anyone else has the same issue!
Well according to wp_update_post(codex) you have to pass the
POST_ID
and I am not sure if your$attach_id
is the post ID, according toupdate_post_meta($post_id, '_thumbnail_id', $attach_id);
Pass the$post_id