Re: set the FIRST image input to be set as a featured-image/post-thumbnail
Given that you know input name="image-one"
is going to be your featured image, you can check for image-one
as your $file_handler
value in function insert_attachment
after the call to media_handle_upload
, then set the thumbnail. See the following code.
Do note that I set image-one
as the field name to look for and pass it every time.
<?php
$thumbnail_field = 'image-one';
if ( ! empty( $_FILES ) ) {
foreach ( $_FILES as $file => $array )
$newupload = insert_attachment( $file, $pid, $thumbnail_field );
}
//attachment helper function
function insert_attachment( $file_handler, $post_id, $set_thumb = false ) {
if ( UPLOAD_ERR_OK !== $_FILES[ $file_handler ]['error'] )
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 );
//set post thumbnail (featured)
if ( $attach_id && $set_thumb )
update_post_meta( $post_id, '_thumbnail_id', $attach_id );
return $attach_id;
}
?>
Re: assign any chosen image-input-field as a featured-image
I think this part isn’t needed as you should just label the first image field as “Featured Image”. It’s possible the submitter doesn’t want to set a featured image now.
In looking at the code above, replace line $thumbnail_field = 'image-one';
with the following.
if ( ! empty( $_POST[ 'thumbnail-field' ] ) )
$thumbnail_field = esc_html( $_POST[ 'thumbnail-field' ] );
else
$thumbnail_field = 'image-one';
This references a select
field like below. Radio’s and jQuery could be used as well to format and populate.
<label for="thumbnail-field">
Thumbnail field
<select name="thumbnail-field">
<option value="image-one">1st</option>
<option value="image-two">2nd</option>
<option value="image-three">3rd</option>
</select>
</label>
Lastly, you might also refresh your memory on PHP’s POST method uploads and check out WordPress’s coding standards for writing more readable code.