user_trailingslashit()
云策文档标注
概述
user_trailingslashit() 函数根据 WordPress 站点的固定链接设置,自动添加或移除 URL 的尾部斜杠。它通过 'user_trailingslashit' 过滤器提供自定义处理能力。
关键要点
- 函数根据 $wp_rewrite->use_trailing_slashes 设置,使用 trailingslashit() 或 untrailingslashit() 处理 URL
- 接受两个参数:$url(必需,URL 字符串)和 $type_of_url(可选,URL 类型,如 'single'、'category' 等)
- 返回处理后的 URL 字符串,并应用 'user_trailingslashit' 过滤器
- 广泛用于 WordPress 核心的链接生成函数,如 get_permalink()、get_term_link() 等
代码示例
function wpdocs_remove_category( $string, $type ) {
if ( 'single' !== $type && 'category' === $type && false !== strpos( $string, 'category' ) ) {
$url_without_category = str_replace( '/category/', '/', $string );
return trailingslashit( $url_without_category );
}
return $string;
}
add_filter( 'user_trailingslashit', 'wpdocs_remove_category', 100, 2 );注意事项
- 函数行为依赖于全局 $wp_rewrite 对象的 use_trailing_slashes 属性,需确保固定链接设置正确
- 通过 'user_trailingslashit' 过滤器,开发者可以基于 $type_of_url 参数自定义 URL 处理逻辑
- 在 WordPress 2.2.0 版本中引入,是处理 URL 尾部斜杠的标准方法
原文内容
Retrieves a trailing-slashed string if the site is set for adding trailing slashes.
Description
Conditionally adds a trailing slash if the permalink structure has a trailing slash, strips the trailing slash if not. The string is passed through the ‘user_trailingslashit’ filter. Will remove trailing slash from string, if site is not set to have them.
Parameters
$urlstringrequired-
URL with or without a trailing slash.
$type_of_urlstringoptional-
The type of URL being considered (e.g. single, category, etc) for use in the filter. Default empty string.
Source
function user_trailingslashit( $url, $type_of_url = '' ) {
global $wp_rewrite;
if ( $wp_rewrite->use_trailing_slashes ) {
$url = trailingslashit( $url );
} else {
$url = untrailingslashit( $url );
}
/**
* Filters the trailing-slashed string, depending on whether the site is set to use trailing slashes.
*
* @since 2.2.0
*
* @param string $url URL with or without a trailing slash.
* @param string $type_of_url The type of URL being considered. Accepts 'single', 'single_trackback',
* 'single_feed', 'single_paged', 'commentpaged', 'paged', 'home', 'feed',
* 'category', 'page', 'year', 'month', 'day', 'post_type_archive'.
*/
return apply_filters( 'user_trailingslashit', $url, $type_of_url );
}
Hooks
- apply_filters( ‘user_trailingslashit’, string $url, string $type_of_url )
-
Filters the trailing-slashed string, depending on whether the site is set to use trailing slashes.
Changelog
| Version | Description |
|---|---|
| 2.2.0 | Introduced. |
Skip to note 2 content
Divyesh kakrecha
you can remove category from wordpress url. See example below.
function wpdocs_remove_category( $string, $type ) { if ( 'single' !== $type && 'category' === $type && false !== strpos( $string, 'category' ) ) { $url_without_category = str_replace( '/category/', '/', $string ); return trailingslashit( $url_without_category ); } return $string; } add_filter( 'user_trailingslashit', 'wpdocs_remove_category', 100, 2 );