0

I am looking to automatically set the featured image from a URL, I have a plugin that creates new posts and has a link back to the source website, I would like to be able to scrape that link for an image and use it for the featured image.

I have seen something similar when creating posts on http://tsu.co/digitalwear where by adding a link to a website it automatically pulls in an image to use...

1 Answer 1

2

You could create a small plugin for this, here is an small example that will try to download and attach a file based on the url in the excerpt field for the post:

add_action('publish_post', 'auto_featured_image_publish_post');
function auto_featured_image_publish_post($post, $post_id) {

  // check if this post is saved for the first time
  if($post->post_date == $post->post_modified) {

    // we're using the excerpt field, change this to whatever field
    // you're using
    $post = get_post($post_id);
    $htmlURL = $post->post_excerpt;

    // try to load the webpage
    $doc = new DOMDocument();
    $doc->loadHTMLFile($htmlURL);

    // get all image tags
    $images = $doc->getElementsByTagName('img');

    // set the first image as featured image for the post, note that
    // you will have to handle relative urls, in other words
    // if $imageURL isn't an absolute url you'll need to append the
    // value of $post->excerpt
    if(count($images)) {
      $imageURL = $images[0]->getAttribute('src');

      // download image from url
      $tmp = download_url($imageURL);

      $file = array(
        'name' => basename($imageURL),
        'tmp_name' => $tmp
      );

      // create attachment from the uploaded image
      $attachment_id = media_handle_sideload( $file, $post_id );

      // set the featured image
      update_post_meta($post_id, '_thumbnail_id', $attachment_id);
    }
  }
}

The above should work but of course you should add code to handle various errors and perhaps also code to check so the dimensions and the type of the image is valid, scaling the image and so on.

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.