wp_should_replace_insecure_home_url()
云策文档标注
概述
wp_should_replace_insecure_home_url() 函数用于检查 WordPress 是否应自动将站点中的旧 HTTP URL 替换为 HTTPS 版本。它基于站点是否使用 HTTPS、迁移选项和域名一致性来决定,并可通过过滤器自定义行为。
关键要点
- 函数返回布尔值:true 表示应替换不安全的 HTTP URL,false 表示不应替换。
- 默认情况下,当站点从 HTTP 迁移到 HTTPS 时,函数返回 true,以触发前端过滤器替换旧数据库内容中的 URL。
- 可通过 'wp_should_replace_insecure_home_url' 过滤器修改返回值,例如在手动替换 URL 后禁用自动替换。
- 函数内部检查条件包括:wp_is_using_https() 返回 true、'https_migration_required' 选项为真,且 home_url() 和 site_url() 的域名相同。
代码示例
function wp_should_replace_insecure_home_url() {
$should_replace_insecure_home_url = wp_is_using_https()
&& get_option( 'https_migration_required' )
&& wp_parse_url( home_url(), PHP_URL_HOST ) === wp_parse_url( site_url(), PHP_URL_HOST );
return apply_filters( 'wp_should_replace_insecure_home_url', $should_replace_insecure_home_url );
}注意事项
- 此函数自 WordPress 5.7.0 版本引入,主要用于 HTTPS 迁移场景。
- 相关函数包括 wp_is_using_https()、wp_parse_url()、site_url()、home_url()、apply_filters() 和 get_option(),用于支持其功能。
- 函数 wp_replace_insecure_home_url() 依赖此函数的返回值来决定是否执行 URL 替换操作。
原文内容
Checks whether WordPress should replace old HTTP URLs to the site with their HTTPS counterpart.
Description
If a WordPress site had its URL changed from HTTP to HTTPS, by default this will return true, causing WordPress to add frontend filters to replace insecure site URLs that may be present in older database content. The ‘wp_should_replace_insecure_home_url’ filter can be used to modify that behavior.
Source
function wp_should_replace_insecure_home_url() {
$should_replace_insecure_home_url = wp_is_using_https()
&& get_option( 'https_migration_required' )
// For automatic replacement, both 'home' and 'siteurl' need to not only use HTTPS, they also need to be using
// the same domain.
&& wp_parse_url( home_url(), PHP_URL_HOST ) === wp_parse_url( site_url(), PHP_URL_HOST );
/**
* Filters whether WordPress should replace old HTTP URLs to the site with their HTTPS counterpart.
*
* If a WordPress site had its URL changed from HTTP to HTTPS, by default this will return `true`. This filter can
* be used to disable that behavior, e.g. after having replaced URLs manually in the database.
*
* @since 5.7.0
*
* @param bool $should_replace_insecure_home_url Whether insecure HTTP URLs to the site should be replaced.
*/
return apply_filters( 'wp_should_replace_insecure_home_url', $should_replace_insecure_home_url );
}
Hooks
- apply_filters( ‘wp_should_replace_insecure_home_url’, bool $should_replace_insecure_home_url )
-
Filters whether WordPress should replace old HTTP URLs to the site with their HTTPS counterpart.
Changelog
| Version | Description |
|---|---|
| 5.7.0 | Introduced. |