category_link
云策文档标注
概述
本文档介绍了 WordPress 中的 category_link 过滤器,用于在显示前修改分类链接的 URL。开发者可以通过 apply_filters() 函数应用此过滤器,实现自定义链接功能。
关键要点
- category_link 过滤器允许修改分类链接的 URL,参数包括 $termlink(链接 URL)和 $term_id(分类 ID)。
- 该过滤器在 WordPress 5.4.1 中恢复使用,之前曾被弃用,推荐使用 'term_link' 过滤器作为替代。
- 通过 add_filter() 函数可以添加自定义回调函数来修改链接,支持简单和复杂的条件逻辑。
代码示例
function wpdocs_category_link_filter( $termlink ) {
// 修改链接,例如添加查询参数
$termlink .= '?custom_param=1';
return $termlink;
}
add_filter( 'category_link', 'wpdocs_category_link_filter' );function wpdocs_category_link_filter( $termlink, $term_id ) {
// 仅修改 ID 为 5 的分类链接
if ( 5 === $term_id ) {
$termlink = home_url( '/special-category/' );
}
return $termlink;
}
add_filter( 'category_link', 'wpdocs_category_link_filter', 10, 2 );注意事项
使用此过滤器时,需注意其版本历史:在 2.5.0 中被弃用,推荐使用 'term_link' 过滤器,但在 5.4.1 中恢复。确保代码兼容性,避免在旧版本中引发问题。
原文内容
Filters the category link.
Parameters
$termlinkstring-
Category link URL.
$term_idint-
Term ID.
Source
$termlink = apply_filters( 'category_link', $termlink, $term->term_id );
Changelog
| Version | Description |
|---|---|
| 5.4.1 | Restored (un-deprecated). |
| 2.5.0 | Deprecated in favor of ‘term_link’ filter. |
| 1.5.0 | Introduced. |
Skip to note 2 content
Noruzzaman
WordPress hooks provide a powerful way to modify and extend the core functionality of your site. The
apply_filters()function is used to apply filters to a variable, allowing you to modify data before it is used. Thecategory_linkfilter specifically allows you to alter the URL of a category link before it is displayed.Simple Examples
function wpdocs_category_link_filter( $termlink ) { // Modify the term link as needed $termlink .= '?custom_param=1'; return $termlink; } add_filter( 'category_link', 'wpdocs_category_link_filter' );Complex Examples
function wpdocs_category_link_filter( $termlink, $term_id ) { // Modify the term link only for category with ID 5 if ( 5 === $term_id ) { $termlink = home_url( '/special-category/' ); } return $termlink; } add_filter( 'category_link', 'wpdocs_category_link_filter', 10, 2 );By using
apply_filters()with thecategory_linkfilter, you can easily customize the URLs of category links in WordPress. This technique allows you to tailor category links to meet your specific needs.