Programatically creating image attachments from local URLs and setting featured image

The question:

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):

<img src="https://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]

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment