WordPress 实现文章中远程(外链)图片自动本地化的方法

2016-09-26 06:17 4,137 22 条评论 龙笑天下
Dragon主题购买

前几天,突然收到七牛的一封邮件“[七牛云服务] 账户冻结预警”,内容如下图:

WordPress 实现文章中远程(外链)图片自动本地化的方法

账户余额为负,威胁冻结服务...说好的免费服务呢~

之前用的贴图库,不过貌似已经死了...现在七牛又来这么一出,看来这些外链图床不是很靠谱!在 112 兄那发现了一个外链图片本地化的方法,觉得非常不错,为以后的摆脱外链图床做准备!

WordPress 文章中远程图片自动保存到本地服务器,最大的好处就是复制粘贴,方便对文章的转载复制。就现实中而言,并不是所有网站都会全部写原创内容或者想伪原创一下,有些好文章想转载,但是对方网站有可能对图片进了防盗链,而图文比较多的情况下,那么就相当麻烦,而此代码功能可有效的帮助你转载复制。不过,无论载转与否,建议保留出处,这是对原作者的尊重,毕竟人家写得辛苦,编辑也不容易。假使是你自己的原创作品,被人盗去并盗用了作者出处,你一定也会很恼火的。所以,将心比心。

好了,话不多说,进入正题。虽说有不少插件能实现这个功能,比如《WordPress 直接粘贴图片到文章编辑器插件 Imagepaste》,但是,有可能插件太多了,会影响网站的性能或者拖累服务器,降低网站的运行速度。但凡能代码实现的,我们都比较推荐使用代码,集成到 wordpress 主题功能中。

实现方法:

复制下面的代码,然后粘贴到你当前 WordPress 主题的模版函数(functions.php)文件中保存即可。

//自动本地化外链图片
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 ( !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;
}

---- 取自boke112

以后你发表文章时就不用去管文章中的外链图片了,因为上面的代码会自动将文章中包含的外链图片自动保存到本地,是不是很方便的 wordpress 技巧呀。

「点点赞赏,手留余香」

还没有人赞赏,快来当第一个赞赏的人吧!

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

2016-09-13

2016-10-22

发表评论

表情 格式 贴图 链接 私密 签到
Dragon主题购买阿里云特价云服务器1核2G低至86元,N4共享型服务器3年仅需799元腾讯云特价云服务器1核2G 88元/年 2核4G3M688元/3年,更有千元代金券礼包免费领!
评论
正在努力加载中...
扫一扫二维码分享
×
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies. Learn more