term_link
云策文档标注
概述
term_link 是一个 WordPress 过滤器,用于在 get_term_link() 函数输出前修改分类法术语的链接 URL。它允许开发者自定义术语链接,例如调整 URL 结构或添加参数。
关键要点
- 过滤器名称:term_link,应用于术语链接 URL。
- 参数:$termlink(术语链接 URL 字符串)、$term(WP_Term 对象)、$taxonomy(分类法 slug)。
- 用途:在 get_term_link() 函数打印链接前进行过滤,常用于自定义链接格式或重写规则。
- 相关函数:get_term_link() 用于生成分类法术语归档的固定链接。
- 版本历史:自 WordPress 2.5.0 引入。
代码示例
// 示例1:修改特定分类法的链接结构,将 /course-category/ 替换为 /course/
function wpdocs_change_course_category_link( $url, $term, $taxonomy ) {
if ( 'course_category' !== $taxonomy ) {
return $url;
}
return str_replace( '/course-category/', '/course/', $url );
}
add_filter( 'term_link', 'wpdocs_change_course_category_link', 10, 3 );
// 示例2:在链接末尾添加哈希标记
add_filter('term_link', 'term_link_filter', 10, 3);
function term_link_filter( $url, $term, $taxonomy ) {
return $url . "#results";
}注意事项
- 使用此过滤器时,需确保正确处理参数,避免影响其他分类法。
- 修改链接后,可能需要刷新固定链接设置(在“设置”->“固定链接”中点击保存)以应用更改。
- 代码示例展示了常见用例,如调整 slug 或添加后缀,开发者应根据实际需求调整。
原文内容
Filters the term link.
Parameters
$termlinkstring-
Term link URL.
$termWP_Term-
Term object.
$taxonomystring-
Taxonomy slug.
Source
return apply_filters( 'term_link', $termlink, $term, $taxonomy );
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 3 content
Khoi Pro
If you are using a solution to keep same slug for both custom post type and taxonomies, such like:
/course/course-name
/course/course-category-name
You should follow those steps to make it working:
1. Register taxonomy course_category with rewrite slug = ‘course-category’.
2. Register post type course with rewrite slug ‘course’.
2. Add filter to term_link:
function wpdocs_change_course_category_link( $url, $term, $taxonomy ) { if ( 'course_category' !== $taxonomy ) { return $url; } return str_replace( '/course-category/', '/course/', $url ); } add_filter( 'term_link', 'wpdocs_change_course_category_link', 10, 3 );Remember to flush permalink once to apply changes (on Settings / Permalinks).
Skip to note 4 content
Steven Lin
Example migrated from Codex:
Append a hashbang at the end of the url.
add_filter('term_link', 'term_link_filter', 10, 3); function term_link_filter( $url, $term, $taxonomy ) { return $url . "#results"; }