WordPress 6.9 开始 URL 转义函数可以支持 HTTPS作为默认协议
在 WordPress 中使用 esc_url() 或者 esc_url_raw() 函数对链接进行转义处理的时候,如果传递的链接字符串不包含协议(https://、http://等)时,WordPress 会在其前面添加 http://。
但是在 WordPress 6.9 之前只能加 http://,无法加其他协议,比如:https://,所以从 WordPress 6.9 开始,可以支持 HTTPS作为默认协议。
现在当 esc_url() 或者 esc_url_raw() 函数第二个参数 $protocols 中的第一个元素是'https',那么就会在该 URL 前添加 https://,当然第一个元素是其他值时候,当前的行为(添加http://)还是将继续保留。
<?php
/*
* 在保持向后兼容性的前提下,推荐默认使用 "https"。
*
* Example: $url 没有写,$protocols 参数中 'https' 优先.
*
* Output:
* - WordPress >= 6.9: 'https://profiles.wordpress.org'
* - WordPress < 6.9: 'http://profiles.wordpress.org'
*/
echo esc_url( 'profiles.wordpress.org', array( 'https', 'http' ) );
如果 $protocols 参数先包含 'https',然后包含 'http':
- WordPress 6.9 会在不完整的 URL 前添加
https://。 - 而旧版本的 WordPress 是继续在前面添加
http://,类似于$protocols未定义时候,如果改参数只有'https',则esc_url()返回空字符串,因为之前版本支持http作为默认协议。
还是看具体的例子更容易理解:
<?php
/*
* Example 1: $url 中没有协议。
*
* 输出:
* - WordPress >= 6.9: 'http://profiles.wordpress.org'
* - WordPress < 6.9: 'http://profiles.wordpress.org'
*/
echo esc_url( 'profiles.wordpress.org' );
/*
* Example 2: $url 使用 'http' 协议。
*
* 输出:
* - WordPress >= 6.9: 'http://profiles.wordpress.org'
* - WordPress < 6.9: 'http://profiles.wordpress.org'
*/
echo esc_url( 'http://profiles.wordpress.org' );
/*
* Example 3: $url 使用 'https' 协议。
*
* 输出:
* - WordPress >= 6.9: 'https://profiles.wordpress.org'
* - WordPress < 6.9: 'https://profiles.wordpress.org'
*/
echo esc_url( 'https://profiles.wordpress.org' );
/*
* Example 4: $url 中没有协议,然后 $protocols 参数中 'http' 优先.
*
* 输出:
* - WordPress >= 6.9: 'http://profiles.wordpress.org'
* - WordPress < 6.9: 'http://profiles.wordpress.org'
*/
echo esc_url( 'profiles.wordpress.org', array( 'http', 'https' ) );
/*
* Example 5: $url 中没有协议,然后 $protocols 参数中没有 'http'.
*
* 输出:
* - WordPress >= 6.9: 'https://profiles.wordpress.org'
* - WordPress < 6.9: ''
*
* 备注:如果 $protocols 参数中不包含 'http',在 6.9 之前版本
* 如果没有包含有效的协议,就不用通过检测。
*/
echo esc_url( 'profiles.wordpress.org', array( 'https' ) );
/*
* Example 6: $url 中有协议但不在 $protocols 中。
*
* 所有都输出:
* - WordPress >= 6.9: ''
* - WordPress < 6.9: ''
*
* 备注:如果 $protocols 参数中不包含 'http',在 6.9 之前版本
* 如果没有包含有效的协议,就不用通过检测。
*/
echo esc_url( 'https://profiles.wordpress.org', array( 'http' ) );
echo esc_url( 'http://profiles.wordpress.org', array( 'https' ) );
echo esc_url( 'mailto:indana@jon.es', array( 'https', 'http' ) );