Programatically creating image attachments from local URLs and setting featured image

I’m currently working on importing an MovableType blog into WordPress. The blog has several thousand posts, and each post has an image associated with it.

The export file contains references to each image as follows (and as expected):

Read More
<img src="http://domain/path/to/image"> 

I’ve got all the images, and have rewritten all the links in the export file to use the new (local) location. However, the WordPress import process doesn’t actually create attachments for the post, which I need.

So – what’s the best way of doing this – right now I’m thinking about iterating through the set of posts, parsing out any image urls, and creating new posts:

  • post_parent = the actual post
  • post_type = attachment

Questions

  • Is post_guid the image location reference? Or is the path to the image stored somewhere else?

  • Where is featured image set?

  • Is this the best way of doing this?

[I’ve tried using the cache-image plugin, but it borks on the number of posts / images]

Related posts

Leave a Reply

1 comment

  1. Answers:

    Is post_guid the image location
    reference? Or is the path to the image
    stored somewhere else?

    $post->guid is the record in a post which holds the URL for your attachment.

    Where is featured image set?

    featured image is saved as post meta so use update_post_meta() once you have the attachment id:

    update_post_meta( $post->ID, '_thumbnail_id', $attachment_id );
    

    Is this the best way of doing this?

    Its a lot of work for several thousand posts and any way you choose will cause you some “pain” but it seems like a reasonable way of accomplishing this.