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.

I am setting up a small dummy content plugin. What I would like to do is import several posts using wp_insert_post. Then I would like to import several images using wp_insert_attachment and then follow this by setting these imported images as post thumbnails for the various posts that were uploaded. I have the first two steps figured out, it is the third ones logic that I am having trouble with.

I have the entire code pasted here: http://pastebin.com/Gxkhhqga but the general gist is to create an array of posts, and bring them in with

foreach ($add_posts_array as $post){
         wp_insert_post( $post );
};

and then bring in the images with

foreach ( $image_url as $image_url ) {
     $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
     $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); 
     wp_update_attachment_metadata( $attach_id, $attach_data );
 };

I'm having trouble wrapping my head around how I can create a foreach loop which will take each image that was inserted and attach it to each post created. Anybody think they have a solution?

I hope that I'm being clear, I'd be happy to clarify.

share|improve this question
1  
$post_id = wp_insert_post($post) should give you ID of the new inserted post. –  birgire Mar 29 '13 at 2:12

1 Answer 1

up vote 0 down vote accepted

wp_insert_post() return the ID of the post if the post is successfully added to the database. Save this ID in variable, and than create foreach images if you want to attach the same images for each post.

Try something like this:

http://pastebin.com/kGu4ZpBi

share|improve this answer
    
Something like this ended up working. I was struggling with basically taking an array of image links and adding a random one to each post as a post thumbnail. What I ended up doing wrong was not setting the post_id properly right up at the top of the foreach loop like you did. Now there's only one loop and each post pulls in a random image. Code here: pastebin.com/ZH65fRTD –  Jason Hoffmann Mar 29 '13 at 18:00

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.