_truncate_post_slug()
云策文档标注
概述
_truncate_post_slug() 函数用于截断文章 slug,确保其长度不超过指定限制。它处理 URL 编码的 slug,并返回截断后的字符串。
关键要点
- 函数接受两个参数:$slug(必需,要截断的 slug)和 $length(可选,最大长度,默认 200 字符)。
- 如果 slug 长度超过 $length,函数会先尝试解码,然后根据是否已解码使用 substr() 或 utf8_uri_encode() 进行截断。
- 返回截断后的 slug,并移除末尾的 '-' 字符。
- 该函数自 WordPress 3.6.0 版本引入,被 wp_unique_post_slug() 等相关函数使用。
代码示例
function _truncate_post_slug( $slug, $length = 200 ) {
if ( strlen( $slug ) > $length ) {
$decoded_slug = urldecode( $slug );
if ( $decoded_slug === $slug ) {
$slug = substr( $slug, 0, $length );
} else {
$slug = utf8_uri_encode( $decoded_slug, $length, true );
}
}
return rtrim( $slug, '-' );
}
原文内容
Truncates a post slug.
Description
See also
Parameters
$slugstringrequired-
The slug to truncate.
$lengthintoptional-
Max length of the slug. Default 200 (characters).
Default:
200
Source
function _truncate_post_slug( $slug, $length = 200 ) {
if ( strlen( $slug ) > $length ) {
$decoded_slug = urldecode( $slug );
if ( $decoded_slug === $slug ) {
$slug = substr( $slug, 0, $length );
} else {
$slug = utf8_uri_encode( $decoded_slug, $length, true );
}
}
return rtrim( $slug, '-' );
}
Changelog
| Version | Description |
|---|---|
| 3.6.0 | Introduced. |