欢迎光临
我们一直在努力

如何修改wordpress图片路径为相对路径

wordpress网站默认上传的图片路径是绝对路径,如果以后更换域名,或者由http变成https,那么图片就不能正常显示了,改为相对路径就不会有影响。

解决办法一:
修改Wordpress主题根目录下的wp-config.php,这个文件只有在安装好Wordpress之后才会出现,在该文件中加入以下两行代码

define(‘WP_HOME’, ”);
define(‘WP_SITEURL’, ”);

保存,OK了!但是这种修改方式是只能用户网网站根目录,并且使用默认的80端口;

如果你不是用网站的根目录,或者用非80端口,那就用第二种方法:
打开wp-includes/post.php文件,修改函数wp_get_attachment_url(3.7.1在4276行)为如下代码

function wp_get_attachment_url( $post_id = 0 ) {
$file_dir=dirname(__FILE__);
$server_root=$_SERVER[DOCUMENT_ROOT];
$file_dir=substr($file_dir,strlen($server_root));

$file_dir=substr($file_dir,0,-12);
if($file_dir!=”){
$file_dir=’/’.substr($file_dir,1);
}

$post_id = (int) $post_id;
if ( !$post =& get_post( $post_id ) )
return false;

$url = ”;
if ( $file = get_post_meta( $post->ID, ‘_wp_attached_file’, true) ) { //Get attached file

if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
//$url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
$url=$file_dir.”/wp-content/uploads/”.$file;
elseif ( false !== strpos($file, ‘wp-content/uploads’) )
//$url = $uploads['baseurl'] . substr( $file, strpos($file, ‘wp-content/uploads’) + 18 );
$url=$file_dir.”/wp-content/uploads/”.$file;
else
//$url = $uploads['baseurl'] . “/$file”; //Its a newly uploaded file, therefor $file is relative to the basedir.
$url=$file_dir.”/wp-content/uploads/”.$file;
}
}

if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recomended to rely upon this.
$url = get_the_guid( $post->ID );

if ( ‘attachment’ != $post->post_type || empty($url) )
return false;

return apply_filters( ‘wp_get_attachment_url’, $url, $post->ID );
}

这样你以后写的文章里面的多媒体文件路径都是用相对路径了,更换域名空间之后图片地址也不会失效!

下面这段代码也可以试一下,把代码加入到当前theme主题的function.php文件中就可以了:

function relativePathForUploads($fileInfos) {
    global $blog_id;
    $path = get_blog_option($blog_id,'siteurl');
    $fileInfos['url'] = str_replace($path,'',$fileInfos['url']);
    return $fileInfos;
}
add_filter('wp_handle_upload', 'relativePathForUploads');
支付宝扫码打赏 微信扫码打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

未经允许不得转载:军哥驿站 » 如何修改wordpress图片路径为相对路径

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

军哥驿站 建站更专业 更方便

网站开发联系我们