url_shorten()
云策文档标注
概述
url_shorten() 是一个 WordPress 核心函数,用于缩短 URL 字符串,以便作为链接文本显示。它通过移除协议前缀和尾部斜杠,并根据指定长度截断 URL 来实现。
关键要点
- 函数接受两个参数:必需的 $url 字符串和可选的 $length 整数(默认 35)。
- 返回缩短后的 URL 字符串,如果超过长度限制,会添加省略号。
- 内部使用 untrailingslashit() 移除尾部斜杠,并处理 'https://'、'http://' 和 'www.' 前缀。
代码示例
function url_shorten( $url, $length = 35 ) {
$stripped = str_replace( array( 'https://', 'http://', 'www.' ), '', $url );
$short_url = untrailingslashit( $stripped );
if ( strlen( $short_url ) > $length ) {
$short_url = substr( $short_url, 0, $length - 3 ) . '…';
}
return $short_url;
}注意事项
- 该函数从 WordPress 4.4.0 版本开始移至 wp-includes/formatting.php,并添加了 $length 参数。
- 常用于 WP_Links_List_Table::column_url() 等场景,处理链接 URL 列的输出。
原文内容
Shortens a URL, to be used as link text.
Parameters
$urlstringrequired-
URL to shorten.
$lengthintoptional-
Maximum length of the shortened URL. Default 35 characters.
Default:
35
Source
function url_shorten( $url, $length = 35 ) {
$stripped = str_replace( array( 'https://', 'http://', 'www.' ), '', $url );
$short_url = untrailingslashit( $stripped );
if ( strlen( $short_url ) > $length ) {
$short_url = substr( $short_url, 0, $length - 3 ) . '…';
}
return $short_url;
}