Use wp_remote_get to add image to media library

I’m using Embedly to make it easy for a client to add news to their website – basically, they just input a URL, and Embedly grabs the link’s information, and I add it all to post meta for displaying on the front-end. So far, so good.

Currently, I’m using the thumbnail as it’s served from the URL’s website, but what I’d like to do is download the image, add it to the media library, and set it as the featured image. I’m given the image’s URL, and I think I have to use wp_remote_get to download the image, but I have no idea what the rest of the steps are.

Edit: Here’s the relevant bits:

function get_fr_news_embedly( $post_id ) {
$post = get_post( $post_id );

if ( $post->post_type == 'fr_news' ) {

    $embedly_key = '[key goes here]';

    $api = new Embedly\Embedly(array( 'key' => $embedly_key, 'user_agent' => 'Mozilla/5.0 (compatible; mytestapp/1.0)' ));
    $fr_news_url = $post->fr_news_url;

    $fr_news_objs = $api->oembed( $fr_news_url );
    update_post_meta( $post_id, 'fr_news_objs', $fr_news_objs );
    $fr_news_objs = get_post_meta( $post_id, 'fr_news_objs' );

    foreach ($fr_news_objs as $k => $oembed) {
        $oembed = (array) $oembed;

        if (array_key_exists('thumbnail_url', $oembed)) {
            $fr_news_thumbnail_url = $oembed['thumbnail_url'];
            update_post_meta( $post_id, 'fr_news_thumbnail_url', $fr_news_thumbnail_url );
            $image = wp_remote_get( $fr_news_thumbnail_url );
                            // wat do?
        }

The question comes down to this: if you have a url for an image, how do you download that image and add it to the media library?

1 Answer
1

I don’t have a code example to test atm but to download images via an URL, in your case after $image = wp_remote_get( $fr_news_thumbnail_url ); you can use the function:

media_sideload_image($file, $post_id, $desc);

http://codex.wordpress.org/Function_Reference/media_sideload_image

Leave a Comment