如何修改WordPress图片地址为相对路径

1、wp-config.php文件最后加上下面代码:(访问路径会随访问域名改变,很适合网站迁移时使用)

/*设置相对路径*/
$home = 'http://'.$_SERVER['HTTP_HOST'];
 
$siteurl = 'http://'.$_SERVER['HTTP_HOST'];
 
define('WP_HOME', $home);
 
define('WP_SITEURL', $siteurl);

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

//改为相对路径
define('WP_HOME', "");
define('WP_SITEURL', "");

3、如果你不是用网站的根目录,或者用非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 );

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远的WEB小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值