Instantly share code, notes, and snippets.

Embed
What would you like to do?
Download Remote Image Example
<?php
// Require the file that contains the KM_Download_Remote_Image class.
require_once plugin_dir_path( __FILE__ ) . 'inc/class-download-remote-image.php';
/**
* Download a remote image, insert it into the media library
* and set it as a post's featured image.
*
* @param string $post_id The ID of the post.
* @param string $url The URL for the remote image.
*
* @param array $attachment_data {
* Optional. Data to be used for the attachment.
*
* @type string $title The title. Also used to create the filename (ex: name-of-file.png).
* @type string $caption The caption.
* @type string $alt_text The alt text.
* @type string $description The description.
* }
* @return bool True on success or false on failure.
*/
function km_set_remote_image_as_featured_image( $post_id, $url, $attachment_data = array() ) {
$download_remote_image = new KM_Download_Remote_Image( $url, $attachment_data );
$attachment_id = $download_remote_image->download();
if ( ! $attachment_id ) {
return false;
}
return set_post_thumbnail( $post_id, $attachment_id );
}
// Example 1: Here we are downloading and setting Google's logo as the featured image for post 123:
$post_id = 123;
$url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
km_set_remote_image_as_featured_image( $post_id, $url );
// Example 2: Here we are doing the same thing as in example 1, but going a step
// further and setting the image's title, caption, alt text and description:
$post_id = 123;
$post_title = get_the_title( $post_id );
$url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
$attachment_data = array(
'title' = 'Title for the featured image of ' . $post_title,
'caption' = 'Caption for the featured image of ' . $post_title,
'alt_text' = 'Alt text for the featured image of ' . $post_title,
'description' = 'Description for the featured image of ' . $post_title,
);
km_set_remote_image_as_featured_image( $post_id, $url, $attachment_data );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment