代理加盟

2023全新代理计划,一站式模板建站,铜牌代理低至699元送终身VIP,独立代理后台,自营贴牌。

您现在的位置: 麦站网 > 站长学院 > Wordpress教程 >

WordPress代码实现复制的图片自动本地化

来源:本站原创 发布时间:2023-04-23 23:03:37热度:266 ℃我要评论(0

麦站模板建站平台(10年经验),服务数万家企业,固定透明报价。域名注册、主机/服务器、网站源码一站式服务。实体公司,专业团队,值得选择!超过1000套模板已登记版权,合规合法建站,规避版权风险!【点击获取方案】

在WordPress主题中加入远程图片文件自动本地化代码,经常转载文章的朋友应该会用到这个功能。把外链图片自动保存到网站本地,防止外链图片失效造成图片不显示。那么如何实现WordPress远程图片自动本地化?把下面的代码添加到主题的 functions.php 文件里面,以后每当在 wordpress 发布文章时如果文章中含有外链图片就会自动本地化了,无需任何设置操作非常方便。

本文章向大家介绍纯代码实现WordPress文章远程图片(外链)自动本地化,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

001function ecp_save_post($post_id, $post) {
002    global $wpdb;
003    if($post->post_status == 'publish') {
004        $p   = '/<img.*[\s]src=[\"|\'](.*)[\"|\'].*>/iU';
005        $num = preg_match_all($p, $post->post_content, $matches);
006        if ($num) {
007            $wp_upload_dir = wp_upload_dir();
008            set_time_limit(0);
009            $ch = curl_init();
010            curl_setopt($ch, CURLOPT_HEADER, false);
011            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
012            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
013            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
014            curl_setopt($ch, CURLOPT_MAXREDIRS,20);
015            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
016   
017            $ecp_options = $_SERVER['HTTP_HOST'];
018            foreach ($matches[1] as $src) {
019                if (isset($src) && strpos($src, $ecp_options) === false) {
020                    $file_info = wp_check_filetype(basename($src), null);
021                    if ($file_info['ext'] == false) {
022                        date_default_timezone_set('PRC');
023                        $file_name = date('YmdHis-').dechex(mt_rand(100000, 999999)).'.tmp';
024                    } else {
025                        $file_name = dechex(mt_rand(100000, 999999)) . '-' . basename($src);
026                    }
027                    curl_setopt($ch, CURLOPT_URL, $src);
028                    $file_path = $wp_upload_dir['path'] . '/' . $file_name;
029                    $img = fopen($file_path, 'wb');
030                    curl_setopt($ch, CURLOPT_FILE, $img);
031                    $img_data  = curl_exec($ch);
032                    fclose($img);
033   
034                    if (file_exists($file_path) && filesize($file_path) > 0) {
035                        $t   = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
036                        $arr = explode('/', $t);
037                        if (pathinfo($file_path, PATHINFO_EXTENSION) == 'tmp') {
038                            $file_path = ecp_handle_ext($file_path, $arr[1], $wp_upload_dir['path'], $file_name, 'tmp');
039                        } elseif (pathinfo($file_path, PATHINFO_EXTENSION) == 'webp') {
040                            $file_path = ecp_handle_ext($file_path, $arr[1], $wp_upload_dir['path'], $file_name, 'webp');
041                        }
042                        $post->post_content  = str_replace($src, $wp_upload_dir['url'] . '/' . basename($file_path), $post->post_content);
043                        $attachment = ecp_get_attachment_post(basename($file_path), $wp_upload_dir['url'] . '/' . basename($file_path));
044                        $attach_id = wp_insert_attachment($attachment, ltrim($wp_upload_dir['subdir'] . '/' . basename($file_path), '/'), 0);
045                        $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
046                        $ss = wp_update_attachment_metadata($attach_id, $attach_data);
047                    }
048                }
049            }
050            curl_close($ch);
051            $wpdb->update( $wpdb->posts, array('post_content' => $post->post_content), array('ID' => $post->ID));
052        }
053    }
054}
055   
056function ecp_handle_ext($file, $type, $file_dir, $file_name, $ext) {
057    switch ($ext) {
058        case 'tmp':
059            if (rename($file, str_replace('tmp', $type, $file))) {
060                if ('webp' == $type) {
061                    return ecp_image_convert('webp', 'jpeg', $file_dir . '/' . str_replace('tmp', $type, $file_name));
062                }
063                return $file_dir . '/' . str_replace('tmp', $type, $file_name);
064            }
065        case 'webp':
066            if ('webp' == $type) {
067                return ecp_image_convert('webp', 'jpeg', $file);
068            } else {
069                if (rename($file, str_replace('webp', $type, $file))) {
070                    return $file_dir . '/' . str_replace('webp', $type, $file_name);
071                }
072            }
073        default:
074            return $file;
075    }
076}
077   
078function ecp_image_convert($from='webp', $to='jpeg', $image) {
079    $im = imagecreatefromwebp($image);
080    if (imagejpeg($im, str_replace('webp', 'jpeg', $image), 100)) {
081        try {
082            unlink($image);
083        } catch (Exception $e) {
084            $error_msg = sprintf('Error removing local file %s: %s', $image,
085                $e->getMessage());
086            error_log($error_msg);
087        }
088    }
089    imagedestroy($im);
090   
091    return str_replace('webp', 'jpeg', $image);
092}
093   
094function ecp_get_attachment_post($filename, $url) {
095    $file_info  = wp_check_filetype($filename, null);
096    return array(
097        'guid'           => $url,
098        'post_type'      => 'attachement',
099        'post_mime_type' => $file_info['type'],
100        'post_title'     => preg_replace('/\.[^.]+$/', '', $filename),
101        'post_content'   => '',
102        'post_status'    => 'inherit'
103    );
104}
105add_action('save_post', 'ecp_save_post', 120, 2);

 

    转载请注明来源网址:https://www.xiuzhanwang.com/wordpress/5681.html

    发表评论

    评论列表(0条)

       
      QQ在线咨询
      VIP限时特惠