WordPress外链图片免插件本地化教程

🤖 由 星火认知大模型 生成的文章摘要
此内容根据文章生成,并经过人工审核,仅用于文章内容的解释与总结

WordPress是全球最受欢迎的开源博客系统之一,它以其灵活性和易用性而广受赞誉。然而,在运营WordPress博客的过程中,我们有时会遇到一个问题:为了丰富内容,我们常常会引入一些外部的图片链接,但是如果这些链接失效,那么文章中的图片也会随之消失。这时,我们需要将外链图片进行本地化操作,即将网络上的图片保存到自己的服务器上。

幸运的是,WordPress提供了一种简便的方式,通过添加一段代码,我们就可以实现图片的自动本地化。接下来,我将分享这段代码,并告诉你如何将其添加到你的WordPress主题中。

首先,我们需要打开WordPress主题目录下的function.php文件。这个文件是WordPress功能的核心部分,我们可以在其中添加自定义函数来扩展WordPress的功能。在这个文件中,我们将添加一段用于本地化外链图片的代码。

以下是你需要添加的代码。这段代码经过测试,可以在多种情况下正常工作。你可以直接将这段代码复制并粘贴到function.php文件中,但是请确保代码格式的正确性。

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);

注意:保存本地指的不单单是服务器,如果您配置了WordPress的阿里云/腾讯云等对象储存插件,那么对象储存就称之为“本地”。

文章作者:阿库
文章链接:https://akau.cn/8197.html
温馨提示:本文最后更新于2024-05-19 ,如有错误或者已经失效,请留言告知。
版权声明:本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明来自:阿库笔记

给TA打赏
共{{data.count}}人
人已打赏
互联网

国内用户访问Github速度慢,如何获得Github加速访问?

2024-5-18 19:07:47

互联网

提高WordPress网站图片加载速度的4种方法

2024-5-19 17:55:19

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索