We have discussed how posts can be added programmaticallybefore. This comes very much handy when you have to make custom scripts to import content from some cms especially custom ones. But the thing often missed is how to add post image for a particular post programmatically. This is something that is always missed. There very less resources online explaining this. But this is a very straight forward thing and very easy to do.There is this wonderful function that does this beautifully.
media_sideload_image($url,$post_id,$description);

The first argument is the remote url of the image you want to download. The second argument is the post id of the post to which you want to attach the image. The third argument is optional, but will be a description if included.
I’d suggest finding a way to throttle the downloads so that you don’t keep timing out, such as limiting the number of images it pulls in per load and setting the importer to refresh itself between downloads, or using AJAX to do them one at a time asynchronously.

Categories: Wordpress

8 Responses so far.

  1. Evan says:

    Just what I was looking for. Thanks! I was going to try and do all the resizing/database modifications with my own script but this saved me a bunch of effort and headache!

  2. Evan says:

    Actually, this does seem to upload the image but it doesn’t set it as the featured image. Do you know I do that?

  3. safwan says:

    Try using this
    add_post_meta($post_id, ‘_thumbnail_id’, $attachment_id);

  4. Exactly what I was looking for, thanks for posting .

  5. Hey there! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  6. Tierra Muhr says:

    I am impressed with this website, really I am a fan.

Leave a Reply


Twitter updates

Sponsors

  • Cheap reliable web hosting from WebHostingHub.com.
  • Domain name search and availability check by PCNames.com.
  • Website and logo design contests at DesignContest.com.
  • Reviews of the best cheap web hosting providers at WebHostingRating.com.