Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

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.

share|improve this answer
    
media_sideload_image requires id of the post, but i can have it only after images is already on the server.... –  user1692333 Jan 8 '13 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 '13 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 '13 at 22:17
add comment

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.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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