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.


<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'>

<?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

1 Answer 1


Did you read doc for set_post_thumbnail()?

You need either post object or post ID for the set_post_thumbnail() function. The function wp_insert_post() will return post id on success. You can use that post id to set the thumbnail image.

Here is the modification for your last couple of lines

$post_id = wp_insert_post( $my_post );

    // post insertion was failed. Handle it here

//Set Image as thumbnail
set_post_thumbnail($post_id, $attachment_id); //Don't know what to do with this

That should do it.

code not tested


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.