get_category_link()
云策文档标注
概述
get_category_link() 函数用于根据分类 ID 或对象检索分类链接 URL。它内部调用 get_term_link() 并处理错误情况,返回链接字符串或空字符串。
关键要点
- 参数 $category 可以是整数(分类 ID)或对象,为必需参数。
- 返回值:成功时返回链接字符串,分类不存在时返回空字符串。
- 使用时机:最早可在 setup_theme Action 中使用,更早使用(如 plugins_loaded)会导致致命错误。
- 相关函数:get_term_link() 用于生成分类法术语归档链接,is_wp_error() 用于检查 WordPress 错误。
- 注意事项:分类 ID 是 term_id,而非 term_taxonomy_id,两者可能不同,需正确区分以避免错误。
代码示例
// 示例:使用 Bootstrap 5 显示分类列表和计数徽章
<?php
$categories = get_categories();
if ( $categories ) {
echo '<div class="card">';
echo '<div class="card-header">Categorias</div>';
echo '<div class="card-body">';
foreach ( $categories as $category ) {
echo '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">';
echo '<div class="d-flex justify-content-between align-items-center">';
echo esc_html( $category->name );
echo '<span class="badge bg-primary rounded-pill">' . esc_html( $category->count ) . '</span>';
echo '</div>';
echo '</a>';
}
echo '</div>';
echo '</div>';
}
?>
原文内容
Retrieves category link URL.
Description
See also
Parameters
$categoryint|objectrequired-
Category ID or object.
Source
function get_category_link( $category ) {
if ( ! is_object( $category ) ) {
$category = (int) $category;
}
$category = get_term_link( $category );
if ( is_wp_error( $category ) ) {
return '';
}
return $category;
}
Changelog
| Version | Description |
|---|---|
| 1.0.0 | Introduced. |
Skip to note 4 content
Codex
Category Link
<!-- Print a link to this category --> <a href="<?php echo esc_url( $category_link ); ?>" title="Category Name">Category Name</a>Skip to note 5 content
rdmi
Worth remembering that a category_id is a term_id and not a term_taxonomy_id
(And, yes, you can figure that out from reading the code. But these sometimes will be the same, fooling some people into thinking that the term_taxonomy_id was right. But sooner or later you will probably get examples where they are different, and then things do not work right.)
Skip to note 6 content
sammuelhg
Example of a categories list with the Bootstrap 5 card and badge count.
<div class="card border border-0 m-2" style="width: 250px;"> <div class="card-header bg-primary text-white"> <h5>Categorias</h5> </div> term_id ) ) ) . '">; echo '<div class="d-flex justify-content-between align-items-start">'; echo esc_html( $category->name ); echo '<span class="badge bg-primary rounded-pill">' . esc_html( $category->count ) . '</span>'; echo '</div>'; echo '</a>'; } ?> </div>