phpwordpressplugins

Use image from URL as a post thumbnail


I want to use an external image from URL as a post thumbnail, BUT I don't want to download and store the image in my server.

I'm found this code in other question:

    $filename = "thumbnail_".$post_id".jpg";
    $upload_file = wp_upload_bits( $filename, null, @file_get_contents('http://example.com/image.jpg') );
 
    if ( ! $upload_file['error'] ) {
      $filename = $upload_file['file'];
      $wp_filetype = wp_check_filetype($filename, null );
      
      $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_parent'    => $post_id,
        'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
        'post_content'   => '',
        'post_status'    => 'inherit'
      );
     
      $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
      file_put_contents('attachment_id.txt', print_r($attachment_id, true));

      if ( ! is_wp_error( $attachment_id ) ) {
          require_once(ABSPATH . 'wp-admin/includes/image.php');

          $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
          wp_update_attachment_metadata( $attachment_id, $attachment_data );
          set_post_thumbnail( $post_id, $attachment_id );
      }
    }

It downloads the image to my server and also duplicates the image file in my uploads directory (I don't know why)

But I don't want to download the image how can I achieve this?


Solution

  • Assuming this image is just alternative to the featured image - you could store the URL of the image source in the custom field.

    add_post_meta( $post_id, 'image', 'http://example.com/image.jpg' );

    Then you can retrieve this URL anywhere you need to.