最近用wordpress做了个网站,想复制些新闻过来用,但图片是别人的,就想怎么本地化,在网找到了方法,那就保存一下方法。

复制下面的代码,然后粘贴到你当前WordPress主题的模版函数(functions.php)文件中保存即可。

//将远程图片地址 本地化 这个在前台编辑器中使用时会有问题
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;
}
$current_user = wp_get_current_user();
if ($current_user->user_login == '网站管理员用户名') { //只允许管理员使用本地化,因为前端编辑器使用会报错,使用前先填入自己的管理员用户名
add_filter('content_save_pre', 'post_save_images');
}

最新文章

  1. 前端之jquery
  2. [java]OutOfMemoryError 原因及解决办法
  3. SpringMVC常用配置-添加静态资源处理器-针对SpringMVC中静态资源无法访问的问题
  4. JAVA网络编程
  5. 自定义listview的步骤
  6. Java基础(56):Java---Assertion的试用(华为OJ里的Java题目的用例检测就是用的断言)
  7. shell下的作业管理[转]
  8. 转:基于ASP.NET的Comet长连接技术解析
  9. iOS学习之界面间传值
  10. jquery获取复选框
  11. FTP的主动和被动模式详解
  12. 双硬盘RAID 0全攻略
  13. CSS3和H5的新特性
  14. threejs绕轴转,粒子系统,控制器操作等(二)
  15. openssl error while loading serial number
  16. Java中的值传递与引用传递
  17. left join 右表数据不唯一的情况解决方法
  18. 运维自动化ansible基础
  19. How to transfer developer profile to one mac to another mac
  20. java 获取class文件所在路径

热门文章

  1. 【java se】java注解
  2. 从一个URL加载一个Document
  3. Struts中整合的强大Ognl学习(一)
  4. mongodb重启报错解决
  5. RapidSVN设置diff和edit工具
  6. CSS布局中最小高度的妙用
  7. Jenkins拉取Git远程仓库中指定目录至本地指定目录
  8. Java clone() 方法克隆对象——深拷贝与浅拷贝
  9. 性能测试工具JMeter 基础(七)—— 测试元件: 逻辑控制器之if逻辑控制器
  10. MySQL——MySQL安装