函数文档

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.

Return

string Absolute path.

Source

function wp_make_link_relative( $link ) {
	return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
}

Changelog

Version Description
4.1.0 Support was added for relative URLs.
2.1.0 Introduced.

User Contributed Notes