wordpress批量将外链图片保存到本地媒体库的插件

今天分享一个可以把wordpress文章中的外链图片批量保存到本地并自动替换外链图片为本地图片链接的插件。

插件功能

1、批量将外链图片保存到本地;

2、自动批量将外链图片链接专为本地链接;

以上两步同时进行,不需要额外的操作。

使用方法

下载插件后,上传并启用插件,按照下面的方法操作:

1、单篇文章操作

在文章编辑界面,点击“更新”按钮,即可自动下载外链图片到本地。
不过逐个编辑文章不仅繁琐而且工作量不小,这里教大家一个小技巧,可以批量下载文章中的外链图片。

2、排量操作

该插件的代码不仅可以在正常的编辑页面点击更新按钮触发下载功能,而且可以在后台所有文章列表页面中触发下载图片功能,原理明白了,操作就简单了。
进入WP后台,文章一所有文章,进入文章管理页面,勾选“标题”全选当前页面的所有文章,并选择“编辑”并点击“应用”按钮。

wordpress批量将外链图片保存到本地媒体库的插件

切记,不要更改批量编辑中的任何设置,只需单击“更新”即可。这个过程将触发检查所有选定的文章,并导入外链图片。默认每页只显示20篇文章,如果你的文章较多,并想一次性处理更多的文章,可以打开右上角的“显示选项”,将“每页的项目数”调整为9999,当然要视你的主机配置适当调整文章数量,一次性处理太多文章,会让主机瞬间资源耗尽,造成宕机。

插件下载

大家可以在本页面底部下载插件,另外,附上代码版的教程

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

作者:JackLee,如若转载,请注明出处:https://www.wlwlm.com/article/6014.html

JackLee的头像JackLee超级管理员
上一篇 2024年7月2日 上午1:20
下一篇 2024年7月5日 上午9:50

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

评论列表(1条)

  • commercial truck scales in Kirkuk
    commercial truck scales in Kirkuk 2024年10月10日 下午2:11

    Bwer Company is a top supplier of weighbridge truck scales in Iraq, providing a complete range of solutions for accurate vehicle load measurement. Their services cover every aspect of truck scales, from truck scale installation and maintenance to calibration and repair. Bwer Company offers commercial truck scales, industrial truck scales, and axle weighbridge systems, tailored to meet the demands of heavy-duty applications. Bwer Company’s electronic truck scales and digital truck scales incorporate advanced technology, ensuring precise and reliable measurements. Their heavy-duty truck scales are engineered for rugged environments, making them suitable for industries such as logistics, agriculture, and construction. Whether you’re looking for truck scales for sale, rental, or lease, Bwer Company provides flexible options to match your needs, including truck scale parts, accessories, and software for enhanced performance. As trusted truck scale manufacturers, Bwer Company offers certified truck scale calibration services, ensuring compliance with industry standards. Their services include truck scale inspection, certification, and repair services, supporting the long-term reliability of your truck scale systems. With a team of experts, Bwer Company ensures seamless truck scale installation and maintenance, keeping your operations running smoothly. For more information on truck scale prices, installation costs, or to learn about their range of weighbridge truck scales and other products, visit Bwer Company’s website at bwerpipes.com.