函数文档

wp_update_urls_to_https()

💡 云策文档标注

概述

wp_update_urls_to_https() 函数用于将 WordPress 的 'home' 和 'siteurl' 选项更新为使用 HTTPS 版本的 URL。如果更新后 WordPress 未识别站点正在使用 HTTPS(例如由于常量覆盖了 URL),函数将回滚更改并返回 false。

关键要点

  • 函数将 'home' 和 'siteurl' 选项中的 HTTP 替换为 HTTPS。
  • 更新后,使用 wp_is_using_https() 检查站点是否识别 HTTPS;若未识别,则回滚更改并返回 false。
  • 成功时返回 true,失败时返回 false。

代码示例

function wp_update_urls_to_https() {
	// Get current URL options.
	$orig_home    = get_option( 'home' );
	$orig_siteurl = get_option( 'siteurl' );

	// Get current URL options, replacing HTTP with HTTPS.
	$home    = str_replace( 'http://', 'https://', $orig_home );
	$siteurl = str_replace( 'http://', 'https://', $orig_siteurl );

	// Update the options.
	update_option( 'home', $home );
	update_option( 'siteurl', $siteurl );

	if ( ! wp_is_using_https() ) {
		/*
		 * If this did not result in the site recognizing HTTPS as being used,
		 * revert the change and return false.
		 */
		update_option( 'home', $orig_home );
		update_option( 'siteurl', $orig_siteurl );
		return false;
	}

	// Otherwise the URLs were successfully changed to use HTTPS.
	return true;
}

注意事项

如果常量(如 WP_HOME 或 WP_SITEURL)覆盖了 URL,可能导致 WordPress 无法识别 HTTPS,从而触发回滚。


📄 原文内容

Update the ‘home’ and ‘siteurl’ option to use the HTTPS variant of their URL.

Description

If this update does not result in WordPress recognizing that the site is now using HTTPS (e.g. due to constants overriding the URLs used), the changes will be reverted. In such a case the function will return false.

Return

bool True on success, false on failure.

Source

function wp_update_urls_to_https() {
	// Get current URL options.
	$orig_home    = get_option( 'home' );
	$orig_siteurl = get_option( 'siteurl' );

	// Get current URL options, replacing HTTP with HTTPS.
	$home    = str_replace( 'http://', 'https://', $orig_home );
	$siteurl = str_replace( 'http://', 'https://', $orig_siteurl );

	// Update the options.
	update_option( 'home', $home );
	update_option( 'siteurl', $siteurl );

	if ( ! wp_is_using_https() ) {
		/*
		 * If this did not result in the site recognizing HTTPS as being used,
		 * revert the change and return false.
		 */
		update_option( 'home', $orig_home );
		update_option( 'siteurl', $orig_siteurl );
		return false;
	}

	// Otherwise the URLs were successfully changed to use HTTPS.
	return true;
}

Changelog

Version Description
5.7.0 Introduced.