2013-05-28 1 views
0

다음 코드를 사용하여 페이지의 첫 번째 이미지를 추천 이미지로 업로드했습니다.대체 로컬 파일을 사용하는 wp_remote_get 대체?

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

괜찮 았지만 지금은 항상 깨진 이미지를 첨부하는 것 같습니다. 이 cloudflare 문제를 일으키는 지 궁금하고 - -

사람이 경험이 있습니까하지만 난 그것을 사용하지 않는 경우, 그것은 여전히 ​​깨진 이미지를 업로드합니다.

이미지의 모든 사이트의 웹 루트에있는 폴더에 저장됩니다 - wp_remote_get을 사용하지 않고 업로드하는 방법은 무엇입니까?

감사

답변

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