九九国产视频_亚洲精品国产三级在线观看_很污很黄能把下面看湿的短文_69色视频日韩在线视频

完整可以的WordPress文章遠程(外鏈)圖片自動保存本地化(親測可用哦)

[重要通告]如您遇疑難雜癥,本站支持知識付費業務,掃右邊二維碼加博主微信,可節省您寶貴時間哦!

有些時候我們在寫文章的時候,難免可能要用到別人的圖片,或者說轉載文章,就要用到了復制文章,但是里面的老是別人的,總歸不好,有一天別人站打不開,在想查看文章的時候,圖片就全是XXX的,感覺會很不爽,如何才能讓讓WordPress遠程文章中圖片本地化呢?方法固然有,插件不少,還是秉著少用一個插件略微安全的原則,還是使用代碼比較好,具體呢請看;

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

//自動本地化外鏈圖片
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();
//以文章的標題作為圖片的標題
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); //每個圖片最長允許下載時間,秒
if(str_replace(get_bloginfo('url'),"",$value)==$value&&str_replace(get_bloginfo('home'),"",$value)==$value){
//判斷是否是本地圖片,如果不是,則保存到服務器
$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;
//添加數據庫記錄
$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;
}

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

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

//自動本地化外鏈圖片
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();
//以文章的標題作為圖片的標題
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); //每個圖片最長允許下載時間,秒
if (str_replace(get_bloginfo('url'), "", $value) == $value && str_replace(get_bloginfo('home'), "", $value) == $value) {
//判斷是否是本地圖片,如果不是,則保存到服務器
$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;
//添加數據庫記錄
$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:值得說明的一下,在老梁博客網站上復制的代碼可能會轉碼成GBK,請使用的時候轉換成U8再使用哦,切記哦,不然會導致網站掛掉的哦~~~具體請看下面的鏈接即可;

復制的PHP文件運行打開是亂碼如何解決?(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);

問題未解決?付費解決問題加Q或微信 2589053300 (即Q號又微信號)右上方掃一掃可加博主微信

所寫所說,是心之所感,思之所悟,行之所得;文當無敷衍,落筆求簡潔。 以所舍,求所獲;有所依,方所成!

支付寶贊助
微信贊助

免責聲明,若由于商用引起版權糾紛,一切責任均由使用者承擔。

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

1 評論

  1. 感謝分享,謝謝站長??!

發表回復

本站承接,網站推廣(SEM,SEO);軟件安裝與調試;服務器或網絡推薦及配置;APP開發與維護;網站開發修改及維護; 各財務軟件安裝調試及注冊服務(金蝶,用友,管家婆,速達,星宇等);同時也有客戶管理系統,人力資源,超市POS,醫藥管理等;

立即查看 了解詳情