2012-06-27 143 views
1

我試圖創建插件導入帖子到WordPress。導入的文章(XML)包含「圖像名稱」屬性,並且此圖像已上傳到服務器。WordPress插件文件「上傳」

但是,我想讓WordPress做它的「魔力」並將圖像導入系統(創建縮略圖,附加到帖子,將其置於wp-uploads目錄模式下)......我發現功能media_handle_upload($file_id, $post_id, $post_data, $overrides),但它需要數組$ _FILES填充實際上傳(並且我沒有上傳文件 - 它已經放在服務器上),所以它不是非常有用

你有任何提示如何繼續?

謝謝

+0

該圖像放置在正確的上傳文件夾或你想它被移動到適當的位置,然後鏈接到帖子? – tamilsweet

+0

它只通過ftp放置在服務器上,它不在wp上傳文件夾中...我想要wordpress在媒體庫中顯示圖像(與帖子鏈接)並將其移動到目錄中... – tomas

回答

2

請檢查以下腳本以獲取此主意。 (它的工作。)

$title = 'Title for the image'; 
    $post_id = YOUR_POST_ID_HERE; // get it from return value of wp_insert_post 
    $image = $this->cache_image($YOUR_IMAGE_URL); 
    if($image) { 
     $attachment = array(
      'guid' => $image['full_path'], 
      'post_type' => 'attachment', 
      'post_title' => $title, 
      'post_content' => '', 
      'post_parent' => $post_id, 
      'post_status' => 'publish', 
      'post_mime_type' => $image['type'], 
      'post_author' => 1 
     ); 

     // Attach the image to post 
     $attach_id = wp_insert_attachment($attachment, $image['full_path'], $post_id); 
     // update metadata 
     if (!is_wp_error($attach_id)) 
     { 
      /** Admin Image API for metadata updating */ 
      require_once(ABSPATH . '/wp-admin/includes/image.php'); 
      wp_update_attachment_metadata 
      ($attach_id, wp_generate_attachment_metadata 
      ($attach_id, $image['full_path'])); 
     } 
    } 

function cache_image($url) { 
    $contents = @file_get_contents($url); 
    $filename = basename($url); 
    $dir = wp_upload_dir(); 
    $cache_path = $dir['path']; 
    $cache_url = $dir['url']; 

    $image['path'] = $cache_path; 
    $image['url'] = $cache_url; 

    $new_filename = wp_unique_filename($cache_path, $filename); 
    if(is_writable($cache_path) && $contents) 
    { 
     file_put_contents($cache_path . '/' . $new_filename, $contents); 

     $image['type'] = $this->mime_type($cache_path . '/' . $new_filename); //where is function mime_type() ??? 

     $image['filename'] = $new_filename; 
     $image['full_path'] = $cache_path . '/' . $new_filename; 
     $image['full_url'] = $cache_url . '/' . $new_filename; 
     return $image; 
    } 
    return false; 
}