wp_remote_get替代使用本地文件?

时间:2013-05-28 19:20:55

标签: php wordpress wordpress-plugin

我一直使用以下代码将页面上的第一张图片上传为精选图片。

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}

function save_first_image(){
    global $post, $posts;
    $first_image = catch_that_image();
    $post_id = $post -> post_id;
    $args = array('timeout' => '1200');
    $get = wp_remote_get( $first_image,$args );

    $type = wp_remote_retrieve_header( $get, 'content-type' );
    $mirror = wp_upload_bits(rawurldecode(basename( $first_image )), '', wp_remote_retrieve_body( $get ) );
    //Attachment options
    $attachment = array(
    'post_title'=> basename( $first_image ),
    'post_mime_type' => $type
    );
    // Add the image to your media library and set as featured image
    $attach_id = wp_insert_attachment( $attachment, $mirror['file'], $post_id );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $first_image );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    set_post_thumbnail( $post_id, $attach_id );
}

它工作正常,但现在似乎总是附着破损的图像。

有没有人有这方面的经验 - 我想知道是不是导致这个问题的云火 - 但是当我禁用它时,它仍然会上传破碎的图像。

所有图片都存储在网站的webroot中的文件夹中 - 有没有办法在不使用wp_remote_get的情况下上传?

由于

1 个答案:

答案 0 :(得分:0)

哈,再说一遍 - 经过几个小时的搜索,在发布后直接找到答案!!

function save_first_image(){
    global $post, $posts;
    $image_url = catch_that_image();
    $post_id = $post -> post_id;
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    if(wp_mkdir_p($upload_dir['path']))
        $file = $upload_dir['path'] . '/' . $filename;
    else
        $file = $upload_dir['basedir'] . '/' . $filename;
    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    set_post_thumbnail( $post_id, $attach_id );
}