WordPress远程图片自动本地化代码亲测可用
WordPress远程图片本地化代码亲测可WordPress远程图片本地化代码亲测可用,本代码适合复制黏贴文章带图片,然后会自动下载远程图片到本地。用,本代码适合复制黏贴文章带图片,然后会自动下载远程图片到本地。支持最新WordPress 6.7.x版本
将以下代码添加到主题functions.php文件中
// 使用代码实现WordPress远程图片本地化
// 自动处理新文章/页面时的钩子
add_action('save_post', 'auto_localize_images', 10, 3);
function auto_localize_images($post_id, $post, $update) {
// 跳过自动保存和修订版本
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($post_id)) return;
// 检查权限和文章类型
if (!current_user_can('edit_post', $post_id)) return;
if (!in_array($post->post_type, ['post', 'page'])) return;
process_images($post_id, $post->post_content);
}
// 处理图片的核心函数
function process_images($post_id, $content) {
// 正则匹配图片
$pattern = '/<img[^>]+src=["\'](.*?)["\']/i';
preg_match_all($pattern, $content, $matches);
if (empty($matches[1])) return;
// 初始化 WordPress 文件系统
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$upload_dir = wp_upload_dir();
$new_content = $content;
$home_url = home_url();
foreach ($matches[1] as $url) {
// 跳过本地图片和无效URL
if (strpos($url, $home_url) !== false || !preg_match('/^https?:\/\//', $url)) {
continue;
}
// 下载图片
$response = wp_remote_get($url, [
'timeout' => 30,
'sslverify' => false,
'headers' => ['Referer' => $home_url]
]);
if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
continue;
}
$image_data = wp_remote_retrieve_body($response);
if (empty($image_data)) continue;
// 获取文件信息
$filename = basename(parse_url($url, PHP_URL_PATH));
if (empty(pathinfo($filename, PATHINFO_EXTENSION))) {
$filename .= '.jpg';
}
$filename = wp_unique_filename($upload_dir['path'], $filename);
$filepath = $upload_dir['path'] . '/' . $filename;
// 保存文件
if (file_put_contents($filepath, $image_data) === false) {
continue;
}
// 创建附件
$filetype = wp_check_filetype($filename);
$attachment = [
'guid' => $upload_dir['url'] . '/' . $filename,
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_file_name(pathinfo($filename, PATHINFO_FILENAME)),
'post_content' => '',
'post_status' => 'inherit'
];
$attach_id = wp_insert_attachment($attachment, $filepath, $post_id);
if (!$attach_id) {
@unlink($filepath);
continue;
}
// 生成附件元数据
$attach_data = wp_generate_attachment_metadata($attach_id, $filepath);
wp_update_attachment_metadata($attach_id, $attach_data);
// 替换URL
$new_url = wp_get_attachment_url($attach_id);
$new_content = str_replace($url, $new_url, $new_content);
}
// 更新文章内容
if ($new_content !== $content) {
remove_action('save_post', 'auto_localize_images');
wp_update_post([
'ID' => $post_id,
'post_content' => $new_content
], true);
add_action('save_post', 'auto_localize_images', 10, 3);
}
}
// 添加后台批量处理功能
add_action('admin_menu', 'register_image_localizer_menu');
function register_image_localizer_menu() {
add_menu_page(
'图片本地化',
'图片本地化',
'manage_options',
'image-localizer',
'image_localizer_admin_page',
'dashicons-images-alt2'
);
}
function image_localizer_admin_page() {
if (!current_user_can('manage_options')) {
wp_die('无权限访问');
}
?>
<div class="wrap">
<h1>远程图片本地化</h1>
<form method="post">
<?php wp_nonce_field('localize_images_action', 'localize_images_nonce'); ?>
<p><input type="submit" name="localize_all" class="button button-primary" value="处理所有文章"></p>
</form>
<?php
if (isset($_POST['localize_all']) && check_admin_referer('localize_images_action', 'localize_images_nonce')) {
set_time_limit(0);
$args = [
'post_type' => ['post', 'page'],
'posts_per_page' => 20, // 每次处理20篇,避免超时
'post_status' => 'publish',
'paged' => 1
];
echo '<div id="localize-progress"><p>正在处理...</p>';
$processed = 0;
do {
$query = new WP_Query($args);
foreach ($query->posts as $post) {
process_images($post->ID, $post->post_content);
$processed++;
echo "<p>已处理文章 #{$post->ID}</p>";
flush();
}
$args['paged']++;
} while ($query->have_posts());
echo "<p>处理完成!共处理 {$processed} 篇文章。</p></div>";
}
?>
</div>
<?php
}
// 提高执行效率
add_filter('http_request_timeout', function($timeout) {
return 30;
});
阅读剩余
版权声明:
作者:LAOV
链接:https://www.laifaka.top/630.html
文章版权归作者所有,未经允许请勿转载。
THE END