有些時候我們編輯文章可能需要將遠程的圖片本地化,常規(guī)的操作是將這個圖片下載到本地然后再上傳進來。實際上這樣確實可以實現(xiàn)只不過效率稍微低一些。有沒有辦法直接復(fù)制到本地編輯器然后自動上傳的,當然是有很多的插件實現(xiàn)。
這里,我們收集到網(wǎng)上流傳的有一個可以不用插件也可以實現(xiàn)的功能。如果有需要的也可以參考,當然這個代碼也有一些問題,比如圖片很多就容易超時。
/** * 參考網(wǎng)絡(luò)整理 * 復(fù)制圖片到本地,提交發(fā)布后自動上傳 * */ function ecp_save_post($post_id, $post) { // wordpress 全局變量 wpdb類 global $wpdb; // 只有在點擊發(fā)布/更新時才執(zhí)行以下動作 if($post->post_status == 'publish') { // 匹配<img>、src,存入$matches數(shù)組, $p = '/<img.*[\s]src=[\"|\'](.*)[\"|\'].*>/iU'; $num = preg_match_all($p, $post->post_content, $matches); if ($num) { // 本地上傳路徑信息(數(shù)組),用來構(gòu)造url $wp_upload_dir = wp_upload_dir(); // 腳本執(zhí)行不限制時間 set_time_limit(0); // 構(gòu)造curl,配置參數(shù) $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 抓取時如果發(fā)生301,302跳轉(zhuǎn),則進行跳轉(zhuǎn)抓取 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 最多跳轉(zhuǎn)20次 curl_setopt($ch, CURLOPT_MAXREDIRS,20); // 發(fā)起連接前最長等待時間 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $ecp_options = $_SERVER['HTTP_HOST']; foreach ($matches[1] as $src) { if (isset($src) && strpos($src, $ecp_options) === false) { // 如果圖片域名不是本站域名 // 檢查src中的url有無擴展名,沒有則重新給定文件名 // 注意:如果url中有擴展名但格式為webp,那么返回的file_info數(shù)組為 ['ext' =>'','type' =>''] $file_info = wp_check_filetype(basename($src), null); if ($file_info['ext'] == false) { // 無擴展名和webp格式的圖片會被作為無擴展名文件處理 date_default_timezone_set('PRC'); $file_name = date('YmdHis-').dechex(mt_rand(100000, 999999)).'.tmp'; } else { // 有擴展名的圖片重新給定文件名防止與本地文件名沖突 $file_name = dechex(mt_rand(100000, 999999)) . '-' . basename($src); } // 抓取圖片, 將圖片寫入本地文件 curl_setopt($ch, CURLOPT_URL, $src); $file_path = $wp_upload_dir['path'] . '/' . $file_name; $img = fopen($file_path, 'wb'); // curl寫入$img curl_setopt($ch, CURLOPT_FILE, $img); $img_data = curl_exec($ch); fclose($img); if (file_exists($file_path) && filesize($file_path) > 0) { // 將擴展名為tmp和webp的圖片轉(zhuǎn)換為jpeg文件并重命名 $t = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $arr = explode('/', $t); // 對url地址中沒有擴展名或擴展名為webp的圖片進行處理 if (pathinfo($file_path, PATHINFO_EXTENSION) == 'tmp') { $file_path = ecp_handle_ext($file_path, $arr[1], $wp_upload_dir['path'], $file_name, 'tmp'); } elseif (pathinfo($file_path, PATHINFO_EXTENSION) == 'webp') { $file_path = ecp_handle_ext($file_path, $arr[1], $wp_upload_dir['path'], $file_name, 'webp'); } // 替換文章內(nèi)容中的src $post->post_content = str_replace($src, $wp_upload_dir['url'] . '/' . basename($file_path), $post->post_content); // 構(gòu)造附件post參數(shù)并插入媒體庫(作為一個post插入到數(shù)據(jù)庫) $attachment = ecp_get_attachment_post(basename($file_path), $wp_upload_dir['url'] . '/' . basename($file_path)); // 生成并更新圖片的metadata信息 $attach_id = wp_insert_attachment($attachment, ltrim($wp_upload_dir['subdir'] . '/' . basename($file_path), '/'), 0); $attach_data = wp_generate_attachment_metadata($attach_id, $file_path); // 直接調(diào)用wordpress函數(shù),將metadata信息寫入數(shù)據(jù)庫 $ss = wp_update_attachment_metadata($attach_id, $attach_data); } } } curl_close($ch); // 更新posts數(shù)據(jù)表的post_content字段 $wpdb->update( $wpdb->posts, array('post_content' => $post->post_content), array('ID' => $post->ID)); } } } /** * 處理沒有擴展名的圖片:轉(zhuǎn)換格式或更改擴展名 * @param string $file 圖片本地絕對路徑 * @param string $type 圖片mimetype * @param string $file_dir 圖片在本地的文件夾 * @param string $file_name 圖片名稱 * @param string $ext 圖片擴展名 * @return string 處理后的本地圖片絕對路徑 */ function ecp_handle_ext($file, $type, $file_dir, $file_name, $ext) { switch ($ext) { case 'tmp': if (rename($file, str_replace('tmp', $type, $file))) { if ('webp' == $type) { // 將webp格式的圖片轉(zhuǎn)換為jpeg格式 return ecp_image_convert('webp', 'jpeg', $file_dir . '/' . str_replace('tmp', $type, $file_name)); } return $file_dir . '/' . str_replace('tmp', $type, $file_name); } case 'webp': if ('webp' == $type) { // 將webp格式的圖片轉(zhuǎn)換為jpeg格式 return ecp_image_convert('webp', 'jpeg', $file); } else { if (rename($file, str_replace('webp', $type, $file))) { return $file_dir . '/' . str_replace('webp', $type, $file_name); } } default: return $file; } } /** * 圖片格式轉(zhuǎn)換,暫只能從webp轉(zhuǎn)換為jpeg * * @param string $from * @param string $to * @param string $image 圖片本地絕對路徑 * @return string 轉(zhuǎn)換后的圖片絕對路徑 */ function ecp_image_convert($from='webp', $to='jpeg', $image) { // 加載 WebP 文件 $im = imagecreatefromwebp($image); // 以 100% 的質(zhì)量轉(zhuǎn)換成 jpeg 格式并將原webp格式文件刪除 if (imagejpeg($im, str_replace('webp', 'jpeg', $image), 100)) { try { unlink($image); } catch (Exception $e) { $error_msg = sprintf('Error removing local file %s: %s', $image, $e->getMessage()); error_log($error_msg); } } imagedestroy($im); return str_replace('webp', 'jpeg', $image); } /** * 構(gòu)造圖片post參數(shù) * * @param string $filename * @param string $url * @return array 圖片post參數(shù)數(shù)組 */ function ecp_get_attachment_post($filename, $url) { $file_info = wp_check_filetype($filename, null); return array( 'guid' => $url, 'post_type' => 'attachement', 'post_mime_type' => $file_info['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), 'post_content' => '', 'post_status' => 'inherit' ); } // 鉤子, 發(fā)布/草稿/預(yù)覽時觸發(fā) add_action('save_post', 'ecp_save_post', 120, 2);
評論