你如何从你的帖子中的URL导入图片?

时间:2015-02-15 作者:Piero Bosco

我正在寻找从一个URL自动设置特色图像,我有一个插件,可以创建新的帖子,并有一个链接回源网站,我想能够刮一个图像的链接,并使用它的特色图像。

我在上创建帖子时也看到过类似的情况http://tsu.co/digitalwear 通过向网站添加链接,它会自动拉入图像以供使用。。。

1 个回复
SO网友:Cyclonecode

您可以为此创建一个小插件,下面是一个小示例,它将尝试根据excerpt 职位字段:

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);
    }
  }
}
上述方法应该可行,但您当然应该添加代码来处理各种错误,还可能添加代码来检查图像的尺寸和类型是否有效,缩放图像等等。

结束

相关推荐

Images with excerpt function

我有一个很好的摘录功能,可以让我的段落保持得体。顺便说一句,效果很好。 function pietergoosen_custom_wp_trim_excerpt($text) { global $post; $raw_excerpt = $text; if ( \'\' == $text ) { $text = get_the_content(\'\'); $text = strip_shortcodes( $text ); &#x