37、wordpress文章内图片如何自动本地化-文公子副业-兼职-网赚-赚钱项目
欢迎您光临本站,秉承服务宗旨,履行"站长"责任,销售只是起点,服务永无止境!

37、wordpress文章内图片如何自动本地化

作者 : 文公子副业 本文共1651个字,预计阅读时间需要5分钟 发布时间: 2023-06-15 共101人阅读

使用场景:转载/采集文章的时候,使用的图片是对方网站的链接。一来不便于SEO。另外如果对方链接失效了,那图片就没了。而以下代码可以让你把远程图片自动本地化

使用配置

1、插件法

nicen-localize-image

QQWorld Auto Save Images

Automatic Upload Images

Auto Upload Images

2、代码法

把下面的代码添加到主题的 functions.php 文件或者是 functions.php 的引入文件中即可,以后每当在 wordpress 发布文章时如果文章中含有外链图片就会自动本地化了,无需任何设置操作非常方便。

//将远程图片地址 本地化 这个在前台编辑器中使用时会有问题
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');
}
文公子副业是文公子创盟旗下的副业,兼职,网赚网站。
文公子副业-兼职-网赚-赚钱项目 » 37、wordpress文章内图片如何自动本地化

常见问题FAQ

免费下载或者VIP会员专享资源能否直接商用?
本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。

发表回复

开通VIP 享更多特权,建议使用QQ登录