wp_internal_hosts()
云策文档标注
概述
wp_internal_hosts() 函数返回一个被视为内部主机的 URL 主机数组,用于判断链接是否指向站点自身。默认基于 home_url() 的主机名构建,可通过过滤器 wp_internal_hosts 自定义。
关键要点
- 函数返回 string[] 类型的 URL 主机数组,用于区分内部和外部链接,例如在应用 nofollow 属性时。
- 默认内部主机列表包含 home_url() 解析出的主机名,通过 wp_parse_url() 处理。
- 支持 wp_internal_hosts 过滤器,允许开发者自定义内部主机列表,数组元素会被转换为小写并去重。
- 相关函数包括 wp_is_internal_link()(用于判断链接是否内部)、wp_parse_url() 和 home_url()。
- 首次发布于 WordPress 6.2.0 版本。
代码示例
function wp_internal_hosts() {
static $internal_hosts;
if ( empty( $internal_hosts ) ) {
/**
* Filters the array of URL hosts which are considered internal.
*
* @since 6.2.0
*
* @param string[] $internal_hosts An array of internal URL hostnames.
*/
$internal_hosts = apply_filters(
'wp_internal_hosts',
array(
wp_parse_url( home_url(), PHP_URL_HOST ),
)
);
$internal_hosts = array_unique(
array_map( 'strtolower', (array) $internal_hosts )
);
}
return $internal_hosts;
}注意事项
- 函数使用静态变量缓存内部主机数组,以提高性能,避免重复计算。
- 过滤器 wp_internal_hosts 的参数为字符串数组,修改时需确保格式正确,以保持一致性。
原文内容
Returns an array of URL hosts which are considered to be internal hosts.
Description
By default the list of internal hosts is comprised of the host name of the site’s home_url() (as parsed by wp_parse_url() ).
This list is used when determining if a specified URL is a link to a page on the site itself or a link offsite (to an external host). This is used, for example, when determining if the “nofollow” attribute should be applied to a link.
See also
- wp_is_internal_link
Source
function wp_internal_hosts() {
static $internal_hosts;
if ( empty( $internal_hosts ) ) {
/**
* Filters the array of URL hosts which are considered internal.
*
* @since 6.2.0
*
* @param string[] $internal_hosts An array of internal URL hostnames.
*/
$internal_hosts = apply_filters(
'wp_internal_hosts',
array(
wp_parse_url( home_url(), PHP_URL_HOST ),
)
);
$internal_hosts = array_unique(
array_map( 'strtolower', (array) $internal_hosts )
);
}
return $internal_hosts;
}
Hooks
- apply_filters( ‘wp_internal_hosts’, string[] $internal_hosts )
-
Filters the array of URL hosts which are considered internal.
Changelog
| Version | Description |
|---|---|
| 6.2.0 | Introduced. |