_links_add_base()
云策文档标注
概述
_links_add_base() 是一个 WordPress 回调函数,用于在传递的内容中为相对链接添加基础 URL。它通过正则表达式匹配链接,并根据协议判断是否使用 WP_Http::make_absolute_url() 进行绝对 URL 转换。
关键要点
- 函数用途:作为回调函数,处理内容中的相对链接,添加基础 URL 以生成绝对链接。
- 参数:接受一个匹配数组 $m,包含链接的属性名、引号和 URL 部分。
- 返回值:返回处理后的链接字符串。
- 核心逻辑:检查 URL 是否使用允许的协议(通过 wp_allowed_protocols()),如果是则保留原 URL,否则使用 WP_Http::make_absolute_url() 转换为绝对 URL。
- 相关函数:依赖 WP_Http::make_absolute_url() 和 wp_allowed_protocols() 实现功能。
- 版本历史:自 WordPress 2.7.0 版本引入。
代码示例
function _links_add_base( $m ) {
global $_links_add_base;
// 1 = attribute name 2 = quotation mark 3 = URL.
return $m[1] . '=' . $m[2] .
( preg_match( '#^(w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols(), true ) ?
$m[3] :
WP_Http::make_absolute_url( $m[3], $_links_add_base )
)
. $m[2];
}
原文内容
Callback to add a base URL to relative links in passed content.
Parameters
$mstringrequired-
The matched link.
Source
function _links_add_base( $m ) {
global $_links_add_base;
// 1 = attribute name 2 = quotation mark 3 = URL.
return $m[1] . '=' . $m[2] .
( preg_match( '#^(w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols(), true ) ?
$m[3] :
WP_Http::make_absolute_url( $m[3], $_links_add_base )
)
. $m[2];
}
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |