纯代码实现WordPress远程图片本地化
WordPress测试版本:5.4
//将远程图片地址 本地化 这个在前台编辑器中使用时会有问题
function post_save_images($content) {
set_time_limit(240);
global $post;
$post_id = $post->ID;
$preg = preg_match_all('/<img.*?src="(.*?)"/', stripslashes($content) , $matches);
if ($preg) {
$i = 1;
foreach ($matches[1] as $image_url) {
if (empty($image_url)) continue;
$pos = strpos($image_url, get_bloginfo('url'));
if ($pos === false) {
$file = file_get_contents($image_url);
$filename = basename($image_url);
//preg_match( '/(.*?)(\.\w+)$/', $filename, $match );
$im_name = $filename;
$res = wp_upload_bits($im_name, '', $file);
$dirs = wp_upload_dir();
$filetype = wp_check_filetype($file);
$attachment = array(
'guid' => $dirs['baseurl'] . '/' . _wp_relative_upload_path($file) ,
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($file)) ,
//preg_replace 搜索并替换
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $file, $id);
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
//wp_generate_attachment_metadata
wp_update_attachment_metadata($attach_id, $attach_data);
//if($i==1 ){
//set_post_thumbnail( $post_id, $attach_id );
//}
$replace = $res['url'];
$content = str_replace($image_url, $replace, $content);
}
$i++;
}
}
remove_filter('content_save_pre', 'post_save_images');
return $content;
}
if (is_admin()) {//只允许管理员使用本地化
add_filter('content_save_pre', 'post_save_images');
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。