At the moment i am working on database conversation script from other cms to Wordpress and faced one problem: I have a list of images, so i need to upload it to Wordpress, after it receive new link, change it with the old one in the post and insert this post. So i wondering if is possiple after wp_insert_post somehow assign image id's to the post which just been inserted.

P.S. And also is there a method that after upload return url of file?

2 Answers 2


Wordpress attachments are saved in the wp_posts table with the post_type field set to 'attachment'. The post id for the post that the attachment is 'linked' to is in the post_parent field. Keep in mind that an attachment being 'linked to a post is not really a solid connection. It is very possible to have an attachment linked to a post but not actually embedded into that post, and equally possible for the same attachment to actually be embedded into a completely different post. (Lets just call it an open relationship.)

Conversions are difficult, but if you adding the post programatically and you have the post id for it, if you are creating the attachment using wp_insert_post(), you can specify post_parent in your post array:

'post_parent'    => [ <post ID> ] //Sets the parent of the new post.

See the media_handle_upload and media_sideload_image functions to upload images and attach them to a post. You can get the url of a specific size with the returned attachment ID and the wp_get_attachment_image_src function.

  • media_sideload_image requires id of the post, but i can have it only after images is already on the server.... Jan 8, 2013 at 21:59
  • you'll have to create the post first and wp_update_post after to modify any embedded urls if you want the image to actually be attached to the post. if you just want to upload a file you can use wp_handle_upload, but you'll have to generate any other sizes manually, see image_make_intermediate_size.
    – Milo
    Jan 8, 2013 at 22:11
  • and just to clarify, posts do not contain or reference IDs to their child attachments, it's the other way around, attachments have a parent post ID.
    – Milo
    Jan 8, 2013 at 22:17

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.