I have a form where user can upload a file, which creates a post with an attachment. I would like to get this attachment with post id, because this is the only thing I have in my case. Is it possible ?

Thank you,


  • You can try this: wp_get_attachment_url( get_post_thumbnail_id( 'your-post-id' ) ); to get attachment by post id.
    – Bhupen
    Jul 4, 2019 at 8:25
  • get_post_thumbnail_id() returns nothing, although post id is fine...
    – ArbreMojo
    Jul 4, 2019 at 8:34
  • Can you check the same image in your WordPress media?
    – Bhupen
    Jul 4, 2019 at 8:47
  • Well it's not necessarily an image, it's a file, whatever the type is, it could be a .txt . That's why I'm not sure we could get it with get_post_thumbnail_id()...
    – ArbreMojo
    Jul 4, 2019 at 9:05
  • If it is there in your media section in WordPress admin then only you will be able to get that attachment.
    – Bhupen
    Jul 4, 2019 at 9:08

1 Answer 1


yes use this code here you can get attachment id

if(isset($_FILES['myimage']) && ($_FILES['myimage']['size'] > 0)) {
// Get the type of the uploaded file. This is returned as "type/extension"
$arr_file_type = wp_check_filetype(basename($_FILES['myimage']['name']));
$uploaded_file_type = $arr_file_type['type'];
// Set an array containing a list of acceptable formats
$allowed_file_types = array('image/jpg', 'image/jpeg', 'image/gif', 'image/png');
if (in_array($uploaded_file_type, $allowed_file_types)) {
    $upload_overrides = array('test_form' => false);
     $uploaded_file = wp_handle_upload($_FILES['myimage'], $upload_overrides);
    if (isset($uploaded_file['file'])) {
        $file_name_and_location = $uploaded_file['file'];
        $file_title_for_media_library = $imagetitle;
        $attachment = array(
            'post_mime_type' => $uploaded_file_type,
            'post_title' => 'Uploaded image ' . addslashes($file_title_for_media_library),
            'post_content' => '',
            'post_status' => 'inherit'
        // Run the wp_insert_attachment function. This adds the file to the media library and generates the thumbnails. If you wanted to attch this image to a post, you could pass the post id as a third param
        $attach_id = wp_insert_attachment($attachment, $file_name_and_location);//here you get attachment id
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attach_id, $file_name_and_location);
        wp_update_attachment_metadata($attach_id, $attach_data);
        update_post_meta($post_id, 'pluginimage', $attach_id);//update post data by attachment id
        $upload_feedback = false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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