How to save a picture from URI given in a JSON feed

Viewed 33

I read a JSON feed in PHP from an external website. In this feed I have to pictures URI. I’m writing a wordpress plugin to create posts from this JSON feed but I would be able to download the pictures and save them inside my WordPress uploads folder.

Any idea how I can do this?

1 Answers

function to save the image:

function insert_attachment_from_url($url, $parent_post_id = null) {

    if( !class_exists( 'WP_Http' ) )
        include_once( ABSPATH . WPINC . '/class-http.php' );

    $http = new WP_Http();
    $response = $http->request( $url );
    if( $response['response']['code'] != 200 ) {
        return false;
    }

    $upload = wp_upload_bits( basename($url), null, $response['body'] );
    if( !empty( $upload['error'] ) ) {
        return false;
    }

    $file_path = $upload['file'];
    $file_name = basename( $file_path );
    $file_type = wp_check_filetype( $file_name, null );
    $attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
    $wp_upload_dir = wp_upload_dir();

    $post_info = array(
        'guid'           => $wp_upload_dir['url'] . '/' . $file_name,
        'post_mime_type' => $file_type['type'],
        'post_title'     => $attachment_title,
        'post_content'   => '',
        'post_status'    => 'inherit',
    );


    $attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id );

    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    $attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );

    wp_update_attachment_metadata( $attach_id,  $attach_data );
    
    set_post_thumbnail( $parent_post_id, $attach_id );

    return $attach_id;

}

and to run the function:

$image = 'YOUR_IMAGE_URL';
insert_attachment_from_url( $image );
Related