类似代码本来已经都有的,不过这个在最新版的wordpress依然有效所以再贴一次.此代码在wordpress 新版本6.XX中测试可以,特保留此源码供参考:
//将远程图片地址 本地化 这个在前台编辑器中使用时会有问题
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)) ,
//搜索并替换
'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;
}
$current_user = wp_get_current_user();
if ($current_user->user_login == 'admin')
{
//只允许管理员使用本地化,因为前端编辑器使用会报错,使用前先填入自己的管理员用户名
add_filter('content_save_pre', 'post_save_images');
}
近期评论