How to upload post thumbnail while wp_insert_post?

I am trying post submit on front end. All works without thumbnail uploading and setting. Here is my html form.

<form method="post" action="">
    <input type="text" name="title">
    <textarea name="content"></textarea>
    <input type="file" name="thumbnail">
    <input type="submit" name="submit">
</form>

And here is my php code.

<?php
if (isset($_POST['submit'])) {

    global $wpdb;
    require_once ABSPATH . 'wp-admin/includes/image.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';

    $title   = $_POST['title'];
    $content = $_POST['content'];

    # Set Post

    $new_post = array(
        'post_title'    => $title,
        'post_content'  => $content,
        'post_status'   => 'pending',
        'post_type'     => 'post',
    );

    $post_id = wp_insert_post($new_post);

    # Set Thumbnail

    $args = array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_status' => 'pending',
        'post_parent' => $post_id
    );

    $attachments = get_posts($args);

    foreach($attachments as $attachment){
        $attachment_id = media_handle_upload('thumbnail', $attachment->ID);
    }

    if (!is_wp_error($attachment_id)) { 
        set_post_thumbnail($post_id, $attachment_id);
        header("Location: " . $_SERVER['HTTP_REFERER'] . "/?files=uploaded");
    }
}
?>

It creates post ok. But it not sets any thumbnail. I don’t know where i am wrong.

3 Answers
3

In form, you need the code enctype=”multipart/form-data”

<form method="post" action="" enctype="multipart/form-data">

Leave a Comment