Home > Enterprise >  Remote get featured image from external REST API and add it via .php file
Remote get featured image from external REST API and add it via .php file

Time:01-08

Okay, perhaps the question sounds a bit complicated, but here we go:

I have a single.php file where I get a lot of data from an external API. This works perfectly and I even can get the path to the image I want to set as the featured image for my custom type posts, however: I do not know if and how it is possible to set this featured image with this URL within single.php.

Like, doing:

$response = wp_remote_get( "[path][to][featuredimg]"

I know that there are plugins out there, but is there a way to automate this process within my single.php to create the featured image automatically within that file?

Any help/suggestions?

Edit, after trying the solution below:

<?php 

// Set the post ID
$post_id = 1241;

// Set the image URL
$image_url = "$result['data']['image']";

// Download the image
$image_id = media_sideload_image($image_url, $post_id, '', 'id');

// Check for errors
if (is_wp_error($image_id)) {
    // An error occurred. Print the error message
    print_r($image_id);
} else {
    // The image was downloaded successfully. Now set it as the featured image for the post
    set_post_thumbnail($post_id, $image_id);
}

?>

The above does not work. The custom post type does not get updated with a featured image when I check it in wp-admin. Any idea why?

Note: I tried the same thing with a 'normal' post with a different idea; same result, which is no featured image.

CodePudding user response:

Yes, it is possible.

you can use the media_sideload_image function to download the image from the URL and attach it to the post as the featured image.

Let me give you an example:

// Set the post ID
$post_id = 1;

// Set the image URL
$image_url = '[path][to][featuredimg]';

// Download the image
$image_id = media_sideload_image($image_url, $post_id, '', 'id');

// Check for errors
if (is_wp_error($image_id)) {
    // An error occurred. Print the error message
    print_r($image_id);
} else {
    // The image was downloaded successfully. Now set it as the featured image for the post
    set_post_thumbnail($post_id, $image_id);
}
  • Related