How do I set an uploaded image from form to be the featured image of the post.
Here are the basics of my code:
User fills form and uploads image. Submitted form data appears as a custom post type. Image uploaded would be featured image of custom post.
Code
<form method='post' enctype='multipart/form-data'>
First Name: <input type='text' name='fname'>
Message: <textarea name='message'></textarea>
Photo: <input type='file' name='file'>
<input type='submit' name='submit'>
</form>
<?php if(isset($_POST['submit']) && !empty($_POST)) {
//Upload Image
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_id = media_handle_upload('file',30);
if (is_wp_error($attachment_id)) {
echo 'BIG TIME ERROR'; }
else {
echo 'BIG TIME SUCCESS';}
//Insert Post
$my_post = array(
'post_title' => $_POST['fname'],
'post_content' => $_POST['message'],
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(8,39),
'post_type' => 'my_custom_post'
);
wp_insert_post( $my_post );
//Set Image as thumbnail
set_post_thumbnail($my_post, $attachment_id); //Don't know what to do with this
?>
I have done research and it looks like the function that does that is set_post_thumbnail
or update_post_meta
?
I'll appreciate any answers with extra information