纯代码实现wordpress图片本地化【5.2.2版本可用】
2024-08-30 22:42:22
最近用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');
}
最新文章
- 前端之jquery
- [java]OutOfMemoryError 原因及解决办法
- SpringMVC常用配置-添加静态资源处理器-针对SpringMVC中静态资源无法访问的问题
- JAVA网络编程
- 自定义listview的步骤
- Java基础(56):Java---Assertion的试用(华为OJ里的Java题目的用例检测就是用的断言)
- shell下的作业管理[转]
- 转:基于ASP.NET的Comet长连接技术解析
- iOS学习之界面间传值
- jquery获取复选框
- FTP的主动和被动模式详解
- 双硬盘RAID 0全攻略
- CSS3和H5的新特性
- threejs绕轴转,粒子系统,控制器操作等(二)
- openssl error while loading serial number
- Java中的值传递与引用传递
- left join 右表数据不唯一的情况解决方法
- 运维自动化ansible基础
- How to transfer developer profile to one mac to another mac
- java 获取class文件所在路径