I am trying to upload featured image from frontend and my id is also inserted in post_meta but image is not uploaded in media library


Here is my code.

            $uploaddir = wp_upload_dir();
            $file = $_FILES['cptFeatured'];

            $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] );

            move_uploaded_file( $file["tmp_name"] , $uploadfile );
            $filename = basename( $uploadfile );

            $wp_filetype = wp_check_filetype(basename($filename['name']), null );

            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
                'post_content' => '',
                'post_status' => 'inherit',
                'menu_order' => $_i + 1000

            $attach_id = wp_insert_attachment( $attachment, $uploadfile, $cpt_id );

            update_post_meta($cpt_id, '_thumbnail_id', $attach_id);
            set_post_thumbnail( $cpt_id, $attach_id );  

cptFeatured is name of input field. and cpt_id is post id.

  • What's your code? Commented Apr 13, 2018 at 10:39
  • @JacobPeattie I have updated my question.
    – user141720
    Commented Apr 13, 2018 at 10:53
  • Does the image show up inside your uploads folder?
    – Swen
    Commented Apr 13, 2018 at 11:18
  • @Swen yes it is in uploads/2018/04 folder but it is of only 1 size. and it is not generating more images of different size like wordpress do.
    – user141720
    Commented Apr 13, 2018 at 11:39

1 Answer 1


You are using the wp_insert_attachment() function, which states the following in the Codex:

This function is part of the low-level API used by WordPress for handling attachments. To perform the entire attachment upload and insertion process at once, you will want to use media_handle_upload() instead in most cases.

So to automatically generate the image resizes and an attachment entry in the database, use the media_handle_upload() function instead.


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.