I've read through a lot of code snippets now and it seems like wether I'm to stupid or there is no solution for this.
I have a setup where some information for a product is loaded via amazon API if I enter the ASIN code in a meta box when creating a post. When I save the post, the Amazon product image is automatically shown in the post. But it isn't attached to the post. It loads from the amazon site.
Now I want the featured image / thumbnail be set automatically. The two options I can think of are:
Option 1. When I save the post, the productimage is uploaded / attached to the post and then somehow set as featured image.
or
Option 2. When the post is published, it is scanned and the first element in -tags is set as featured image.
I really don't know where to start here! (obviously I'm also open to other approaches)
Edit:
I found this code but don't know where to start with it. Does it look right to you? And where do I put it?
/** Set Featured Image **/
// required libraries for media_sideload_image
function featuredimagesetter($post_id)
{
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$post_id == how do I set this?;
$image_thumb_url == 'http://www.examplesite.com/exampleimage.jpg';
// load the image
$result = media_sideload_image($image_thumb_url, $post_id, 'image_thumbnail');
// then find the last image added to the post attachments
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
if(sizeof($attachments) > 0){
// set image as the post thumbnail
set_post_thumbnail($post_id, $attachments[0]->ID);
}
add_action('save_post','featuredimagesetter');
}
This might set the featured image to the image I set. But if this works I guess it won't be a big deal to set the image to a variable instead of the imagepath. But still I don't know how to set the $pot_id correctly and if the whole code should work and where I have to put it.