盛龙科技

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)) ,
                    //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 == 'admin') { //只允许管理员使用本地化,因为前端编辑器使用会报错,使用前先填入自己的管理员用户名
    add_filter('content_save_pre', 'post_save_images');
}
Q1 免费下载或者VIP会员资源能否直接商用?
本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
Q2 提示下载完但解压或打开不了?
最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。 若排除这种情况,可在对应资源底部留言,或联络我们。
Q3 找不到素材资源介绍文章里的示例图片?
对于会员专享、整站源码、程序插件、网站模板、网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
Q4 付款后无法显示下载地址或者无法查看内容?
如果您已经成功付款但是网站没有弹出成功提示,请联系站长提供付款信息为您处理
Q5 购买该资源后,可以退款吗?
源码素材属于虚拟商品,具有可复制性,可传播性,一旦授予,不接受任何形式的退款、换货要求。请您在购买获取之前确认好 是您所需要的资源

评论交流(0)

发表评论

相关推荐