完整可以的WordPress文章遠(yuǎn)程(外鏈)圖片自動(dòng)保存本地化(親測(cè)可用哦)

[重要通告]如您遇疑難雜癥,本站支持知識(shí)付費(fèi)業(yè)務(wù),掃右邊二維碼加博主微信,可節(jié)省您寶貴時(shí)間哦!

有些時(shí)候我們?cè)趯?xiě)文章的時(shí)候,難免可能要用到別人的圖片,或者說(shuō)轉(zhuǎn)載文章,就要用到了復(fù)制文章,但是里面的老是別人的,總歸不好,有一天別人站打不開(kāi),在想查看文章的時(shí)候,圖片就全是XXX的,感覺(jué)會(huì)很不爽,如何才能讓讓WordPress遠(yuǎn)程文章中圖片本地化呢?方法固然有,插件不少,還是秉著少用一個(gè)插件略微安全的原則,還是使用代碼比較好,具體呢請(qǐng)看;

百度了一下,網(wǎng)上都是很多的ctrl+c然后加V,復(fù)制粘貼類型,也都不測(cè)試,根本就是不能用的代碼;比如(網(wǎng)上都是這個(gè)109行代碼的保存):

//自動(dòng)本地化外鏈圖片
add_filter('content_save_pre', 'auto_save_image');
function auto_save_image($content) {
$upload_path = '';
$upload_url_path = get_bloginfo('url');
//上傳目錄
if (($var = get_option('upload_path')) !=''){
$upload_path = $var;
} else {
$upload_path = 'wp-content/uploads';
}
if(get_option('uploads_use_yearmonth_folders')) {
$upload_path .= '/'.date("Y",time()).'/'.date("m",time());
}
//文件地址
if(($var = get_option('upload_url_path')) != '') {
$upload_url_path = $var;
} else {
$upload_url_path = bloginfo('url');
}
if(get_option('uploads_use_yearmonth_folders')) {
$upload_url_path .= '/'.date("Y",time()).'/'.date("m",time());
}
require_once ("../wp-includes/class-snoopy.php");
$snoopy_Auto_Save_Image = new Snoopy;
$img = array();
//以文章的標(biāo)題作為圖片的標(biāo)題
if ( !emptyempty( $_REQUEST['post_title'] ) )
$post_title = wp_specialchars( stripslashes( $_REQUEST['post_title'] ));
$text = stripslashes($content);
if (get_magic_quotes_gpc()) $text = stripslashes($text);
preg_match_all("/ src=(\"|\'){0,}(http:\/\/(.+?))(\"|\'|\s)/is",$text,$img);
$img = array_unique(dhtmlspecialchars($img[2]));
foreach ($img as $key => $value){
set_time_limit(180); //每個(gè)圖片最長(zhǎng)允許下載時(shí)間,秒
if(str_replace(get_bloginfo('url'),"",$value)==$value&&str_replace(get_bloginfo('home'),"",$value)==$value){
//判斷是否是本地圖片,如果不是,則保存到服務(wù)器
$fileext = substr(strrchr($value,'.'),1);
$fileext = strtolower($fileext);
if($fileext==""||strlen($fileext)>4)
$fileext = "jpg";
$savefiletype = array('jpg','gif','png','bmp');
if (in_array($fileext, $savefiletype)){
if($snoopy_Auto_Save_Image->fetch($value)){
$get_file = $snoopy_Auto_Save_Image->results;
}else{
echo "error fetching file: ".$snoopy_Auto_Save_Image->error."<br>";
echo "error url: ".$value;
die();
}
$filetime = time();
$filepath = "/".$upload_path;//圖片保存的路徑目錄
!is_dir("..".$filepath) ? mkdirs("..".$filepath) : null;
//$filename = date("His",$filetime).random(3);
$filename = substr($value,strrpos($value,'/'),strrpos($value,'.')-strrpos($value,'/'));
//$e = '../'.$filepath.$filename.'.'.$fileext;
//if(!is_file($e)) {
// copy(htmlspecialchars_decode($value),$e);
//}
$fp = @fopen("..".$filepath.$filename.".".$fileext,"w");
@fwrite($fp,$get_file);
fclose($fp);
$wp_filetype = wp_check_filetype( $filename.".".$fileext, false );
$type = $wp_filetype['type'];
$post_id = (int)$_POST['temp_ID2'];
$title = $post_title;
$url = $upload_url_path.$filename.".".$fileext;
$file = $_SERVER['DOCUMENT_ROOT'].$filepath.$filename.".".$fileext;
//添加數(shù)據(jù)庫(kù)記錄
$attachment = array(
'post_type' => 'attachment',
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => '',
);
$id = wp_insert_attachment($attachment, $file, $post_parent);
$text = str_replace($value,$url,$text); //替換文章里面的圖片地址
}
}
}
$content = AddSlashes($text);
remove_filter('content_save_pre', 'auto_save_image');
return $content;
}
function mkdirs($dir)
{
if(!is_dir($dir))
{
mkdirs(dirname($dir));
mkdir($dir);
}
return ;
}
function dhtmlspecialchars($string) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = dhtmlspecialchars($val);
}
}else{
$string = str_replace('&', '&', $string);
$string = str_replace('"', '"', $string);
$string = str_replace('<', '<', $string);
$string = str_replace('>', '>', $string);
$string = preg_replace('/&(#\d;)/', '&\1', $string);
}
return $string;
}

我也是用了此代碼,然后看我使用的效果;遠(yuǎn)程圖片可以正常下載在,但是在顯示文章會(huì)出現(xiàn)路徑不正確;是不是,這就很尷尬了,那就自己動(dòng)手豐衣足食,那我們就來(lái)操作一下吧;

修改后的代碼(非常滴可用):

//自動(dòng)本地化外鏈圖片
add_filter('content_save_pre', 'auto_save_image');
function auto_save_image($content) {
$upload_path = '';
$upload_url_path = get_bloginfo('url');
//上傳目錄
if (($var = get_option('upload_path')) != '') {
$upload_path = $var;
} else {
$upload_path = 'wp-content/uploads';
}
if (get_option('uploads_use_yearmonth_folders')) {
$upload_path.= '/' . date("Y", time()) . '/' . date("m", time());
}
//文件地址
if (($var = get_option('upload_url_path')) != '') {
$upload_url_path = $var;
} else {
$upload_url_path = get_bloginfo('url');
}
if (get_option('uploads_use_yearmonth_folders')) {
$upload_url_path.= '/wp-content/uploads/' . date("Y", time()) . '/' . date("m", time());
}
require_once ("../wp-includes/class-snoopy.php");
$snoopy_Auto_Save_Image = new Snoopy;
$img = array();
//以文章的標(biāo)題作為圖片的標(biāo)題
if (!empty($_REQUEST['post_title'])) $post_title = wp_specialchars(stripslashes($_REQUEST['post_title']));
$text = stripslashes($content);
if (get_magic_quotes_gpc()) $text = stripslashes($text);
preg_match_all("/ src=(\"|\'){0,}(http:\/\/(.+?))(\"|\'|\s)/is", $text, $img);
$img = array_unique(dhtmlspecialchars($img[2]));
foreach ($img as $key => $value) {
set_time_limit(180); //每個(gè)圖片最長(zhǎng)允許下載時(shí)間,秒
if (str_replace(get_bloginfo('url'), "", $value) == $value && str_replace(get_bloginfo('home'), "", $value) == $value) {
//判斷是否是本地圖片,如果不是,則保存到服務(wù)器
$fileext = substr(strrchr($value, '.'), 1);
$fileext = strtolower($fileext);
if ($fileext == "" || strlen($fileext) > 4) $fileext = "jpg";
$savefiletype = array('jpg', 'gif', 'png', 'bmp');
if (in_array($fileext, $savefiletype)) {
if ($snoopy_Auto_Save_Image->fetch($value)) {
$get_file = $snoopy_Auto_Save_Image->results;
} else {
echo "error fetching file: " . $snoopy_Auto_Save_Image->error . "<br>";
echo "error url: " . $value;
die();
}
$filetime = time();
$filepath = "/" . $upload_path; //圖片保存的路徑目錄
!is_dir(".." . $filepath) ? mkdirs(".." . $filepath) : null;
//$filename = date("His",$filetime).random(3);
$filename = substr($value, strrpos($value, '/'), strrpos($value, '.') - strrpos($value, '/'));
//$e = '../'.$filepath.$filename.'.'.$fileext;
//if(!is_file($e)) {
// copy(htmlspecialchars_decode($value),$e);
//}
$fp = @fopen(".." . $filepath . $filename . "." . $fileext, "w");
@fwrite($fp, $get_file);
fclose($fp);
$wp_filetype = wp_check_filetype($filename . "." . $fileext, false);
$type = $wp_filetype['type'];
$post_id = (int)$_POST['temp_ID2'];
$title = $post_title;
$url = $upload_url_path . $filename . "." . $fileext;
$file = $_SERVER['DOCUMENT_ROOT'] . $filepath . $filename . "." . $fileext;
//添加數(shù)據(jù)庫(kù)記錄
$attachment = array('post_type' => 'attachment', 'post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => '',);
$id = wp_insert_attachment($attachment, $file, $post_parent);
$text = str_replace($value, $url, $text); //替換文章里面的圖片地址

}
}
}
$content = AddSlashes($text);
remove_filter('content_save_pre', 'auto_save_image');
return $content;
}
function mkdirs($dir) {
if (!is_dir($dir)) {
mkdirs(dirname($dir));
mkdir($dir);
}
return;
}
function dhtmlspecialchars($string) {
if (is_array($string)) {
foreach ($string as $key => $val) {
$string[$key] = dhtmlspecialchars($val);
}
} else {
$string = str_replace('&', '&', $string);
$string = str_replace('"', '"', $string);
$string = str_replace('<', '<', $string);
$string = str_replace('>', '>', $string);
$string = preg_replace('/&(#\d;)/', '&\1', $string);
}
return $string;
}

PS:值得說(shuō)明的一下,在老梁博客網(wǎng)站上復(fù)制的代碼可能會(huì)轉(zhuǎn)碼成GBK,請(qǐng)使用的時(shí)候轉(zhuǎn)換成U8再使用哦,切記哦,不然會(huì)導(dǎo)致網(wǎng)站掛掉的哦~~~具體請(qǐng)看下面的鏈接即可;

復(fù)制的PHP文件運(yùn)行打開(kāi)是亂碼如何解決?(PHP GBK編碼變UTF-8)

2023年1月1日更新一次:


function ecp_save_post($post_id, $post) {
    global $wpdb;
    if($post->post_status == 'publish') {
        $p   = '/<img.*[\s]src=[\"|\'](.*)[\"|\'].*>/iU';
        $num = preg_match_all($p, $post->post_content, $matches);
        if ($num) {
            $wp_upload_dir = wp_upload_dir();
            set_time_limit(0);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_MAXREDIRS,20);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  
            $ecp_options = $_SERVER['HTTP_HOST'];
            foreach ($matches[1] as $src) {
                if (isset($src) && strpos($src, $ecp_options) === false) {
                    $file_info = wp_check_filetype(basename($src), null);
                    if ($file_info['ext'] == false) {
                        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_setopt($ch, CURLOPT_FILE, $img);
                    $img_data  = curl_exec($ch);
                    fclose($img);
  
                    if (file_exists($file_path) && filesize($file_path) > 0) {
                        $t   = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
                        $arr = explode('/', $t);
                        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');
                        }
                        $post->post_content  = str_replace($src, $wp_upload_dir['url'] . '/' . basename($file_path), $post->post_content);
                        $attachment = ecp_get_attachment_post(basename($file_path), $wp_upload_dir['url'] . '/' . basename($file_path));
                        $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);
                        $ss = wp_update_attachment_metadata($attach_id, $attach_data);
                    }
                }
            }
            curl_close($ch);
            $wpdb->update( $wpdb->posts, array('post_content' => $post->post_content), array('ID' => $post->ID));
        }
    }
}
  
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) {
                    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) {
                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;
    }
}
  
function ecp_image_convert($from='webp', $to='jpeg', $image) {
    $im = imagecreatefromwebp($image);
    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);
}
  
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'
    );
}
add_action('save_post', 'ecp_save_post', 120, 2);

問(wèn)題未解決?付費(fèi)解決問(wèn)題加Q或微信 2589053300 (即Q號(hào)又微信號(hào))右上方掃一掃可加博主微信

所寫(xiě)所說(shuō),是心之所感,思之所悟,行之所得;文當(dāng)無(wú)敷衍,落筆求簡(jiǎn)潔。 以所舍,求所獲;有所依,方所成!

支付寶贊助
微信贊助

免責(zé)聲明,若由于商用引起版權(quán)糾紛,一切責(zé)任均由使用者承擔(dān)。

您必須遵守我們的協(xié)議,如您下載該資源,行為將被視為對(duì)《免責(zé)聲明》全部?jī)?nèi)容的認(rèn)可->聯(lián)系老梁投訴資源
LaoLiang.Net部分資源來(lái)自互聯(lián)網(wǎng)收集,僅供用于學(xué)習(xí)和交流,請(qǐng)勿用于商業(yè)用途。如有侵權(quán)、不妥之處,請(qǐng)聯(lián)系站長(zhǎng)并出示版權(quán)證明以便刪除。 敬請(qǐng)諒解! 侵權(quán)刪帖/違法舉報(bào)/投稿等事物聯(lián)系郵箱:service@laoliang.net
意在交流學(xué)習(xí),歡迎贊賞評(píng)論,如有謬誤,請(qǐng)聯(lián)系指正;轉(zhuǎn)載請(qǐng)注明出處: » 完整可以的WordPress文章遠(yuǎn)程(外鏈)圖片自動(dòng)保存本地化(親測(cè)可用哦)

1 評(píng)論

  1. 感謝分享,謝謝站長(zhǎng)?。?/p>

發(fā)表回復(fù)

本站承接,網(wǎng)站推廣(SEM,SEO);軟件安裝與調(diào)試;服務(wù)器或網(wǎng)絡(luò)推薦及配置;APP開(kāi)發(fā)與維護(hù);網(wǎng)站開(kāi)發(fā)修改及維護(hù); 各財(cái)務(wù)軟件安裝調(diào)試及注冊(cè)服務(wù)(金蝶,用友,管家婆,速達(dá),星宇等);同時(shí)也有客戶管理系統(tǒng),人力資源,超市POS,醫(yī)藥管理等;

立即查看 了解詳情