wp_make_link_relative()
云策文档标注
概述
wp_make_link_relative() 函数用于将完整的 URL 路径转换为绝对路径,移除协议和域名,保留开头的 '/',使其基于网站根目录。
关键要点
- 移除 URL 中的 http 或 https 协议和域名部分
- 返回以 '/' 开头的绝对路径,而非真正的相对链接
- 接受一个必需参数 $link,为完整的 URL 路径字符串
- 返回字符串类型的绝对路径
- 在 WordPress 4.1.0 版本中添加了对相对 URL 的支持,最初在 2.1.0 版本引入
- 注意:当网站使用非标准端口时,此函数可能无法按预期工作
代码示例
// 基本示例
echo wp_make_link_relative('https://example.com/wp_test/sample-page/');
// 输出: /wp_test/sample-page/
// 使用文章 ID 的示例
echo wp_make_link_relative(get_permalink($post->ID));
// 或当前文章
echo wp_make_link_relative(get_permalink());注意事项
- 此函数不适用于使用非标准端口的网站,可能导致输出如 ':8080/wp_test/sample-page/' 的错误格式
- 函数内部使用正则表达式实现:preg_replace('|^(https?:)?//[^/]+(/?.*)|i', '$2', $link)
原文内容
Converts full URL paths to absolute paths.
Description
Removes the http or https protocols and the domain. Keeps the path ‘/’ at the beginning, so it isn’t a true relative link, but from the web root base.
Parameters
$linkstringrequired-
Full URL path.
Source
function wp_make_link_relative( $link ) {
return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
}
Skip to note 4 content
Codex
Basic Example
This should output the following URL:
Skip to note 5 content
arifktk
Example with Post ID:
echo wp_make_link_relative(get_permalink( $post->ID ));Where
$postis your post object.Example for current post:
echo wp_make_link_relative(get_permalink());Skip to note 6 content
Jake Jackson
Be aware that this function does not work as expected when a site uses a non-standard port.
will output
/wp_test/sample-page/.