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.


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)


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); 

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.

2 Answers 2


I recently released a plugin that imports any external images found in a post and imports them into the media library, attaches them to the post and sets the first image found as the featured image.


I'm posting the basic function that gets the external image and sets it as the featured image. In the plugin this is done through an admin page via ajax but you could add it to the save_post hook as Milo mentions in his answer.

function process_image() {
    $response = '';
    $data[] = '';
    $error = 0;

    $img = $this->extract_image( $post );
        if( empty( $img ) ) {
            $response .=  'No images found <br>';
            die( sprintf( $response . '<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error  > 0 ? $error : 'no' ) );

    /** @var $file string or WP_Error of image attached to the post  */
    $file = media_sideload_image( $img, (int)$post->ID );
    if ( is_wp_error( $file ) ) {
        $response .= '<span style="color:red">Upload Error: Could not upload image. Check for malformed img src url</span><br>';
    } else {
        $atts = $this->get_attach( $post->ID );
        foreach ( $atts as $a ) {
           $img = set_post_thumbnail( $post->ID, $a['ID'] );
           if ( $img ) {
              $thumb = wp_get_attachment_thumb_url( $a['ID'] );
              $response .= '<img src="'.esc_url( $thumb ).'" /><br>';
              $response .= '<a href="' . wp_nonce_url( get_edit_post_link( $a['ID'], true ) ) . '" >' . get_the_title( $a['ID'] ) . '</a>  Set as Featured Image</p><br>';
    unset( $atts );
    unset( $a );
    return $response;

This is not meant to be copied and pasted. It is an example of how to do this and the code will need to be adapted to your specific situation. This code is inside a class and the $response variable gets returned via ajax in my plugin.

The function that is called in the above code to extract the image:

 * Extracts the first image in the post content
 * @param object $post the post object
 * @return bool|string false if no images or img src
function extract_image( $post ) {
    $html = $post->post_content;
    if ( stripos( $html, '<img' ) !== false ) {
        $regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
        preg_match( $regex, $html, $matches );
        unset( $regex );
        unset( $html );
        if ( is_array( $matches ) && ! empty( $matches ) ) {
            return  $matches[2];

        } else {
            return false;
    } else {
        return false;

The get_attach function called that gets the attachments:

 * Queries for attached images
 * @param int $post_id The post id to check if attachments exist
 * @return array|bool The 1st attached on success false if no attachments
function get_attach( $post_id ) {
    return get_children( array (
            'post_parent'    => $post_id,
            'post_type'      => 'attachment',
            'post_mime_type' => 'image',
            'posts_per_page'  => (int)1
        ), ARRAY_A );

I'm not familiar with the Amazon API, but if you're handy with a bit of php you could make this happen.

There's the save_post hook, which, if you're familiar with how meta boxes work, you should also be familiar with.

I assume you can fetch an image using that Amazon product number. Attach it to a post via the media_handle_sideload() function, then add post meta with meta key _thumbnail_id and the returned attachment ID to set that image as featured image.

  • Thanks for the answer. I edited my question and used a code snippet that uses this technique, but still got no solution ;)
    – nucci
    Jul 1, 2012 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.