0

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.

  • 1
    $post_id = wp_insert_post($post) should give you ID of the new inserted post. – birgire Mar 29 '13 at 2:12
0

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

  • 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

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.