I am trying to make a script that allows me to set the featured image of a certain post. For some reason it is not working. Could anyone tell me why?

$post_id = ... // We get the ID from the form

if (isset($_FILES['thumbnail'])) {
    $uploaded_file = $_FILES['userfile'];
    $filename      = $uploaded_file['name'];
    $tmp_file      = $uploaded_file['tmp_name'];
    $upload_dir    = wp_upload_dir();
    $end_file      = $upload_dir['path']."/$filename";

    move_uploaded_file($tmp_file, $end_file);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => sanitize_file_name($filename),
        'post_content'   => '',
        'post_status'    => 'inherit'
    $attach_id = wp_insert_attachment($attachment, $end_file, $post_id);
    set_post_thumbnail($post_id, $attach_id);

Read more here: WordPress – Uploading the featured image for a post programatically


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Wordpress related questions and answers: